ActiveRecord fails to update HABTM relation

家住魔仙堡 提交于 2019-12-12 19:32:12

问题


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.

I tried to created a user interface for assigning roles to users with simple checkboxes - just like in Railscasts Episode #17.

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.

Manually assigning roles with @user.roles or @user.role_ids works, but not the "magic" inside User#new or User#update_attributes.

Any ideas?


回答1:


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

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.



来源:https://stackoverflow.com/questions/755774/activerecord-fails-to-update-habtm-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!