I wanted to start using attr_accessible with my models to stop the problem with mass assignment. I understand how it works and have researched as much as I could.
What I don’t understand is the difference between using update_attributes(params[:my_form]) or create(params[:my_form]) and setting the fields one by one? Aren’t both just as vulnerable?
What is the difference between NOT having attr_accessible and doing this…
@model_object = ModelObject.new
@model_object.create(params[:model_object_params])
And having attr_accessible and doing this…
@model_object = ModelObject.new
@model_object.field1 = params[:model_object_params][:field1]
@model_object.field2 = params[:model_object_params][:field2]
@model_object.field3 = params[:model_object_params][:field3]
@model_object.save!
Aren’t both these methods of creating the record just as vulnerable? The hacker/cracker could send a url to both these methods and both would do just the same, right?
Or does using attr_accessible and updating the fields one-by-one do something different or somehow become safer?
There’s where all these methods I’m finding of using attr_accessible don’t make any sense to me. It seems to be doing the same thing two different ways. What am I missing?
Thanks.
In the way you are doing it, it does not prevent “mass assignment”.
“Mass assignment” is the term used when Rails is handling the assigning of values to attributes in a model. This is typically done in a controller, using the names and values in
params.When you’re doing the assigning yourself, it is also “mass assignment”, in a way; but you have fine control over what to assign and what not to in this case. So, to save writing that boilerplate assignment code, Rails provides
attr_accesible– same control, less code.To see how it is used:
Presume that a
ActivityLogmodel has an attribute calleduser_ip_address.Now,
user_ip_addressis an attribute in the model, and could be assigned by mass-assignment or by “self-rolled-mass-assignment”.But in both cases that is wrong — you don’t want user-supplied input to set a value for that attribute.
Instead, you want to always find out the actual IP address of the user and assign that value (ignoring any
value in
params). So you would excludeuser_ip_addressfromattr_accessibleand instead assign it yourself.For any information that a user should not be able to change, use
attr_accessibleand exclude it from the list.