I’ve been into rails recently and I am seeing this MassAssignment Error very often in scenarios where I want to save the child with parent_id.
To fix this everyone are suggesting to add the associated foreign key to the attr_accessbile list.
I could resolve it by doing so but am not sure what happens under the hood. Is it true that whitelisting the foreign_key would pose security problems?
Lets consider the following scenario of models:
class BusinessType < ActiveRecord ::Base
has_one :business_form
validates :name, :presence => true
attr_accesible :name, :enabled
end
class BusinessForm < ActiveRecord ::Base
belongs_to :business_type
validates :name, :presence => true
validates_associated :business_type, :presence=>true
attr_accessible :name, :enabled
end
In the above case whenever I try to save the business_form without business_type_id in attr_accessible list I would get mass assignment error. When I add it to the whitelist I am not getting any error message even the business_type select box is left empty and the form submitted.
I request anyone to shed some light in this area of rails. Please point me to any links that would explain in detail.
Yes, it would pose security problems. Say someone were able to make a post to your BusinessFormController#create and they passed the “business_type_id” as part of the post. If your controller simply creates the record by doing something like this:
then it is allowing the user to specify any business type for that form. I don’t know how your site works, but that might be a problem as certain users may be allowed to create certain types of forms. The main concern with adding foreign keys to attr_accessible is that it’s allowing hackers (anyone who knows web programming at all) to associate this newly created record with any of the foreign key objects. If in this case you don’t care or it’s not restricted, then it may not matter.
If you still want to follow what people are telling you, why not keep the attr_accessible without “business_type_id” in it, but write your action like this: