Rails associations can't mass-assign foreign key
-
28-03-2021 - |
Question
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
Solution
Are you using Rails 3.2.0.rc1? That's a know bug github.com/rails/rails/issues/4051 (resolved)