我是一个铁杆新手,我正在尝试为用户和角色设置一个简单的habtm。 我正在尝试在我的种子文件中为用户分配一个角色,但我总是收到此错误:
无法批量分配受保护的属性:角色
我创建了没有id的链接表,如下所示:
create_table :roles_users, :id => false do |t|
t.references :role, :user
end
我的用户和角色模型如下所示:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
devise :database_authenticatable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :roles_attributes
accepts_nested_attributes_for :roles, :reject_if => :all_blank, :allow_destroy => true
end
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
attr_accessible :name
end
当我尝试在种子文件中为用户分配角色时,如下所示:
#Create a role
role = Role.find_or_create_by_name 'admin'
#Create test user
user = User.find_or_create_by_email 'niels@work.be'
user.update_attributes! password: 'testme', password_confirmation: 'testme', roles: role
rake命令总是停止并抱怨它无法大量分配受保护的属性?
任何人都知道我做错了什么并引导我朝着正确的方向前进? 非常感谢提前!
答案 0 :(得分:0)
roles: [role]
attr_accessible :roles #if required
role_ids: [role.id]
attr_accessible :role_ids #if required