Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails mass assignment definition and attr_accessible use

Just want to be clear on what mass assignment is and how to code around it. Is mass assignment the assignment of many fields using a hash, ie like..

@user = User.new(params[:user])

And to prevent this you use attr_accessible like:

attr_accessible :name, :email

So that a field like :admin could not be added by mass assignment?

But we can modify it in code by something like:

@user.admin = true

So is it true that if we don't have attr_accessible then everything is accessible for mass assignment?

And finally the tricky point ... is it true that even with one attr_accessible like "attr_accessible :name" means that all other fields are now not accessible for mass assignment?

like image 851
rtfminc Avatar asked Mar 11 '11 19:03

rtfminc


People also ask

What is mass assignment Rails?

Mass assignment is a feature of Rails which allows an application to create a record from the values of a hash. Example: User.new(params[:user]) Unfortunately, if there is a user field called admin which controls administrator access, now any user can make themselves an administrator with a query like.

What is Attr_accessible in Ruby?

attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.


2 Answers

All of your assumptions are correct. Without attr_accessible, all fields are open to mass assignment. If you start using attr_accessible, only the fields you specify are open to mass assignment.

like image 143
Srdjan Pejic Avatar answered Nov 01 '22 18:11

Srdjan Pejic


As pointed out by Srdjan all of your assumptions are correct. Just so you know, there is also an attr_protected method which is the opposite of attr_accessible.

In other words

attr_protected :admin

will prevent :admin from being mass-assigned but will allow all other fields.

like image 37
tilleryj Avatar answered Nov 01 '22 17:11

tilleryj