我有这些模型:
class User < ActiveRecord::Base
attr_accessible :email, :name, :roles_user_attributes
has_many :roles_users
has_many :roles, through: :roles_users
accepts_nested_attributes_for :roles_users, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :roles
end
class Role < ActiveRecord::Base
attr_accessible :name, :user_id
has_many :roles_users
has_many :users, through: :roles_users
end
class RolesUser < ActiveRecord::Base
attr_accessible :active, :role_id, :user_id, :role_attributes
belongs_to :user
belongs_to :role
accepts_nested_attributes_for :role, reject_if: :all_blank
end
当我运行时:
my_role = Role.find(1)
user = User.find(1)
user.roles_users.create(active: 1, role: my_role)
我得到了错误Can't mass-assign protected attributes: role
。
当我user.roles_users.create(active: 1, role_id: 1)
改为运行时,它可以工作。
我尝试将roles_user_attributes & role_attributes 更改为roles_users_attributes & roles_attributes,但并没有解决问题。
我阅读了很多关于这个主题的问题,但没有任何解决方案对我有用。你不知道为什么?然而我很困惑。
提前致谢!