12 Marattr_accessible vs attr_protected

Friday, 12 March 2010 — 09:01

I found recently some code where developers tend to have a never-ended list of model attributes like this:

# accessibles
  attr_accessible :category_type_id, :subcategory_type_id, 
                             :cause, :treatment, :prevention, :symptoms, 
                             :recovered, :finishes_at, :historical_id

or

# accessibles
  attr_accessible :category_type_id

This is usually an indicator that something is wrong, moreover when those are almost all the model attributes (first example). attr_accessibles allows mass assignment ONLY on those attributes in the list. That means we have to use write methods for attributes that are not on the list (second example). If you add a new column to that table/model, you need to remember to add that column to the attr_accessibles list.

Probably, it would have been more appropriate to protect JUST those critical attributes with this:

#attr_protected
attr_protected :user_id

In both cases the effect is the same:

record = Record.new(:category_type => "injury", : subcategory_type_id => "ankle", 
                 :treatment => "band", :user_id => '17823456S')
record.user_id # => nil

Ger

Comentarios

Añade tu comentario




(textile habilitado)
Negrita: *Google*
Enlace: "google.com":http://www.google.com
Imagen: !http://ggomeze.com/images/avatar.png!

ó Cancelar