When do you use attr_reader
/attr_writer
/attr_accessor
in Rails models?
Rails models are just ruby classes that inherit from ActiveRecord::Base
. ActiveRecord employs attr_accessor
s to define getters and setters for the column names that refer to the ruby class's table. It's important to note that this is just for persistence; the models are still just ruby classes.
attr_accessor :foo
is simply a shortcut for the following:
def foo=(var)
@foo = var
end
def foo
@foo
end
attr_reader :foo
is simply a shortcut for the following:
def foo
@foo
end
attr_writer :foo
is a shortcut for the following:
def foo=(var)
@foo = var
end
attr_accessor
is a shortcut for the getter and setter while attr_reader
is the shortcut for the getter and attr_writer
is a shortcut for just the setter.
In rails, ActiveRecord uses these getters and setters in a convenient way to read and write values to the database. BUT, the database is just the persistence layer. You should be free to use attr_accessor
and attr_reader
as you would any other ruby class to properly compose your business logic. As you need to get and set attributes of your objects outside of what you need to persist to the database, use the attr_
s accordingly.
More info:
http://apidock.com/ruby/Module/attr_accessor
http://www.rubyist.net/~slagell/ruby/accessors.html
What is attr_accessor in Ruby?