16

If in a model file I have just this code:

class Users < ActiveRecord::Base end 

what this means? All attributes related to the model are accessible or not?

How I can set 'attr_accessible' in order to not allow access to any of the fields for that model?

1
  • 2
    You also asked "All attributes related to the model are accessible or not?" -- by default all fields are accessible for mass-assignment Commented Jan 30, 2011 at 15:19

4 Answers 4

33

Just set:

class Users < ActiveRecord::Base attr_accessible #none end 

Like Pan Thomakos said (attr_accessible is the array of parameters that can be mass-ret. So if you send in no symbols, then no parameters will be accessible.

This ticket was useful

Sign up to request clarification or add additional context in comments.

2 Comments

This is definitely the simplest and best approach. Conversely you could set 'attr_protected :each, :one, :of, :your, :attributes
For future overflowers --- this is valid for Rails 3.2... in Rails 4, you'll handle this using strong_parameters github.com/rails/strong_parameters
11

By default the attributes are all attr_accessible (which means they can be set my mass-assignment).

  • attr_accessible - only this list of attributes can be set by mass-assignment (white-listing).
  • attr_protected - these attributes cannot be set by mass-assignment (black-listing).
  • attr_readonly - these attributes cannot be set except for when the record is created.

To disable mass-assignment entirely, use something like this:

 ActiveRecord::Base.send(:attr_accessible, nil) 

This command will disable mass-assignment for all active record objects, but you can specify one or more models to perform this command on if you want mass-assignment in some cases but not in others.

1 Comment

But how can I "'attr_protected'" all attributes for a specific model?
1

Beginning with Rails 3.1, the following configuration option is available to disable mass-assignment by default for all models until you explicitly call attr_accessible or attr_protected:

config.active_record.whitelist_attributes = true 

See http://edgeguides.rubyonrails.org/security.html#mass-assignment and https://github.com/rails/rails/commit/f3b9d3aba8cc0ffaca2da1c73c4ba96de2066760

Comments

0

I prefer to be more explicit in the denial for one model:

class Users < ActiveRecord::Base attr_accessible nil end 

The result is the same as attr_accessible with no params, but makes your intent more clear. This will reduce the likelihood that a future programmer (e.g. yourself!) will delete the line...or start adding fields to attr_accessible.

This appeases Brakeman and other vulnerability-sniffing tools.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.