Rails mass assignment definition and attr_accessible use
Asked Answered
B

3

17

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?

Barney answered 11/3, 2011 at 19:1 Comment(0)
V
12

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.

Valdovinos answered 11/3, 2011 at 19:6 Comment(0)
A
6

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.

Adin answered 11/3, 2011 at 22:43 Comment(0)
C
3

Srdjan's answer is correct assuming that config.active_record.whitelist_attributes is set to false in your config/application.rb.

If it is set to true, all attributes will be protected from mass assignment by default unless attr_accessible or attr_protected is used.

Counterpane answered 2/3, 2013 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.