我按照本指南创建了用户模型授权: authentication-with-devise-and-cancancan
但是在用户模型中使用admin boolean列而不是角色表。以这种方式更改管理方法(用户模型)
def assign_role
self.admin = false if self.admin.nil?
end
def admin?
self.admin == true
end
一切正常。现在我创建了一个客户模型,然后又重复了同样的教程。当我尝试注册时,我会收到未定义的方法`name'对于current_customer错误。有什么想法吗?
编辑:这是命令行中的代码:
rails g scaffold user name:string
rails g devise User
bundle exec rake db:migrate
rails g scaffold customer name:string
rails g devise Customer
bundle exec rake db:migrate
所以我有客户模型:
class Customer < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
并在架构中:
create_table "customers", force: :cascade do |t|
t.string "name"
t.string "surname"
t.string "nickname"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
end
add_index "customers", ["email"], name: "index_customers_on_email", unique: true, using: :btree
add_index "customers", ["reset_password_token"], name: "index_customers_on_reset_password_token", unique: true, using: :btree
与用户模型的唯一区别是:
validates_presence_of :name
before_save :assign_role
def assign_role
self.admin = false if self.admin.nil?
end
def admin?
self.admin == true
end
和布尔字段&#34; admin&#34;在用户中添加。使用Devise来验证两种不同的模型存在冲突吗? 错误发生在第6行的应用程序布局中:
<div class='container'>
<%= yield %>
<% if customer_signed_in? %>
Signed in as <%= current_customer.name %>. Not you?
<%= link_to "Edit profile", edit_customer_registration_path %>
<%= link_to "Sign out", destroy_customer_session_path, :method => :delete %>
<% else %>
<%= link_to "Sign up", new_customer_registration_path %> or <%= link_to "sign in", new_customer_session_path %>
<% end %>
<% flash.each do |name, msg| %>
<%= content_tag :div, msg, id: "flash_#{name}" %>
<% end %>
</div>
答案 0 :(得分:1)
确保您的模型Customer“具有名为”name“的属性。如果没有,请运行以下rake命令:
$ rails g migration AddNameToCustomer name:string
$ rake db:migrate