Rails 关联无法批量分配外键
也许我做错了,但这是我的问题:
@restaurant = current_user.restaurants.build(params[:restaurant])
这会构建一个新的餐厅对象,其中 user_id 设置为 current_user.id
。仅当您在餐厅模型中设置 attr_accessible :user_id
时,此功能才有效。如果不是,您会得到
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes:
user_id
我想要的是通过 .build
定义 user_id
但同时我不想要 attr_accessible :user_id
因为这样就可能有人将此记录的 user_id 设置为其他用户的 id,这会很糟糕!
我认为外键已从批量分配安全性中排除,并且如果您通过关联 .build
或 .create
方法创建新对象,则外键将被强制执行。
有什么建议吗?我不想回去,
@restaurant = current_user.restaurants.build(params[:restaurant])
@restaurant.user = current_user
因为这违背了 .build
的目的
Maybe I am doing it wrong but here is my issue:
@restaurant = current_user.restaurants.build(params[:restaurant])
This builds a new restaurant object where the user_id is set to the current_user.id
. This only works if you set attr_accessible :user_id
in the Restaurant Model. If not you get a
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes:
user_id
What I want is to have the user_id
defined via .build
but at the same time I do not want the attr_accessible :user_id
because then it is possible for someone to set the user_id of this record to some other user's id, which would be bad!!
I thought the foreign keys were excluded from this Mass Assignment Security and were enforced if you create a new object via the association .build
or .create
methods.
Any suggestions? I dont want to go back to
@restaurant = current_user.restaurants.build(params[:restaurant])
@restaurant.user = current_user
because that kind of defeats the purpose of .build
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用的是 Rails 3.2.0.rc1 吗?这是一个已知的错误 github.com/rails/rails/issues/4051 (已解决)
Are you using Rails 3.2.0.rc1? That's a know bug github.com/rails/rails/issues/4051 (resolved)