1

I am using Ruby on Rails 3.0.9 and I would like to know in which cases (that is, for which methods) the attr_accessible method has effect. For example, if I use

attr_accessible :name, :surname

it will care to not assign those attribute values when you use the new(...) method for the User.new(params[:user]) statement.

But what other methods it will take care? Can I run correctly, for example, methods as where(...) and exists?(...) without that the attr_accessible will take effect?

Backo
  • 18,291
  • 27
  • 103
  • 170

2 Answers2

3

If you use attr_accessible, the model will prevent mass assignment of those columns which are not included in the attr_accessible list. The methods affected are those of mass assignment like new, create, update_attributes, attributes= etc. All other functions will work, even single assignment like this:

@model_object.column_not_listed_in_attr_accessible_list = "Saved"
@model_object.column_not_listed_in_attr_accessible_list
=> "Saved"

So, there should not be any problem for using them in where, exists? etc.

rubyprince
  • 17,559
  • 11
  • 64
  • 104
2

attr_accessible will impact only functions that is related to write operations.

Ex: new, create, update_attributes, etc.

Other read-only functions like where, exists?, etc should not have any impact.

Arun Kumar Arjunan
  • 6,827
  • 32
  • 35
  • For an '@users.update_all(...)' method how can I assign a not 'attr_accessible' attribute value? – Backo Aug 18 '11 at 10:30
  • @backo...For User.update_all, the SQL is directly sent to the database without instantiation of model objects, so `attr_accessible` or `attr_protected` will have no effect here..it will be saved..see [update_all](http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all)...`This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations.` – rubyprince Aug 18 '11 at 10:50