ActiveRecord的无法更新HABTM关系 [英] ActiveRecord fails to update HABTM relation
问题描述
我用了两个ActiveRecords用户授权的简单模型用户
和角色
用户
和角色
有一个HABTM关系到对方。
I'm using a simple model for user authorisation with two ActiveRecords User
and Role
User
and Role
have a HABTM relation to each other.
我试图创建一个用户界面,给用户分配角色与简单的复选框 - 就像在 Railscasts情节#17 。
I tried to created a user interface for assigning roles to users with simple checkboxes - just like in Railscasts Episode #17.
我的问题是,无论是用户#新
和用户#update_attributes的
使用提交我的表单参数更新在用户
对象和它的角色之间的关系。 PARAMS [:用户] [:role_ids]
包含正确的价值观。但调用 @ user.roles
之后 User.new(PARAMS [:用户])
或 @ user.update_attributes(PARAMS [:用户])
返回一个空数组
My problem is that neither User#new
nor User#update_attributes
use the parameters submitted by my form to update the relation between the User
object and its roles. params[:user][:role_ids]
contains the correct values. But calling @user.roles
right after User.new(params[:user])
or @user.update_attributes(params[:user])
returns an empty array.
手动分配的角色与 @ user.roles
或 @ user.role_ids
的作品,但不是的 神奇的内部用户#新
或用户#update_attributes的
。
Manually assigning roles with @user.roles
or @user.role_ids
works, but not the "magic" inside User#new
or User#update_attributes
.
任何想法?
推荐答案
的机会是很高,你有你的用户模型无论是attr_accessible或attr_protected通话,从而使role_ids保护,质量分配。
The chances are high that you have either attr_accessible or attr_protected call in your User model, thus making role_ids protected from mass assignment.
如果你真的想通过大规模的赋值操作符来更新角色,只需添加
If you really want to update roles via mass assignment operators, just add
attr_accessible :role_ids
到模型。不过,我建议你读的http://railspikes.com/2008/9/22/is-your-rails-application-safe-from-mass-assignment第一,只知道质量分配的所有潜在的问题。
to your model. However, I recommend you reading http://railspikes.com/2008/9/22/is-your-rails-application-safe-from-mass-assignment first, just to know all potential problems of mass assignment.
这篇关于ActiveRecord的无法更新HABTM关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!