未定义方法“角色”?
我在使用用户的默认角色播种数据库时遇到问题。
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :username
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
validates_presence_of :username, :email, :password, :password_confirmation
validates_uniqueness_of :username, :email
before_create :setup_default_role_for_new_users
ROLES = %w[admin default]
private
def setup_default_role_for_new_users
self.roles = [ "default" ]
end
end
Seeds.rb
puts 'Loading seed data now....'
user1 = User.create(:username => 'admin', :email => '[email protected]', :password => 'qweasd',:password_confirmation => 'qweasd', :role => 'admin')
user2 = User.create(:username => 'userone', :email => '[email protected]', :password => 'qweasd', :password_confirmation => 'qweasd')
user3 = User.create(:username => 'usertwo', :email => '[email protected]', :password => 'qweasd',:password_confirmation => 'qweasd')
puts 'Users added'
播种时出现错误:
undefined method `roles' for #<User:0x53f4c60>
我的数据库中有 role
列,为什么它不起作用?
I'm having issues seeding my database with the default roles of my users.
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :username
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
validates_presence_of :username, :email, :password, :password_confirmation
validates_uniqueness_of :username, :email
before_create :setup_default_role_for_new_users
ROLES = %w[admin default]
private
def setup_default_role_for_new_users
self.roles = [ "default" ]
end
end
Seeds.rb
puts 'Loading seed data now....'
user1 = User.create(:username => 'admin', :email => '[email protected]', :password => 'qweasd',:password_confirmation => 'qweasd', :role => 'admin')
user2 = User.create(:username => 'userone', :email => '[email protected]', :password => 'qweasd', :password_confirmation => 'qweasd')
user3 = User.create(:username => 'usertwo', :email => '[email protected]', :password => 'qweasd',:password_confirmation => 'qweasd')
puts 'Users added'
When seeding the error I get:
undefined method `roles' for #<User:0x53f4c60>
I have have the role
column in my database so why wouldn't it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望能够批量分配它,请将 :roles 添加到您的 attr_accessible 中:
也是
:role
还是:roles
?检查您的数据库,如果您有:role
或:roles
,请将 schema.db 粘贴到此处。Add :roles to your attr_accessible if you want to be able to mass assign it like in:
also is it
:role
or:roles
? Check your database, if you have:role
or:roles
paste your schema.db here.因为你使用
首先将 user1 设置为 admin (在内存中),然后 before_create 将其设置为默认
类似这样的事情应该可以做到
because you use the
First you set the user1 to admin (in memory) and then the before_create sets it to default
Something like this should do it