Using attr_accessor and attr_accessible on the same field

Magne picture Magne · Jan 15, 2011 · Viewed 17.5k times · Source

What happens in the background with the following code?

class User < ActiveRecord::Base

 attr_accessor :name
 attr_accessible :name

end

Hint: When instantiating the class, will it be persisted to the database? Why or why not?

Answer

pjammer picture pjammer · Jan 15, 2011

attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View.

attr_accessible allows you to list all the columns you want to allow Mass Assignment, as andy eluded to above. The opposite of this is attr_protected which means this field i do NOT want anyone to be allowed to Mass Assign to. More then likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.