user502052
user502052

Reputation: 15259

How I can set 'attr_accessible' in order to NOT allow access to ANY of the fields FOR a model using Ruby on Rails?

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?

Upvotes: 16

Views: 5132

Answers (4)

David Hempy
David Hempy

Reputation: 6237

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.

Upvotes: 0

joealba
joealba

Reputation: 740

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

Upvotes: 1

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

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

Upvotes: 33

Pan Thomakos
Pan Thomakos

Reputation: 34350

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.

Upvotes: 11

Related Questions