Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of attr_accessor in Rails

When do you use attr_reader/attr_writer/attr_accessor in Rails models?

like image 544
Ethan Avatar asked May 08 '10 05:05

Ethan


People also ask

What is the use of Attr_accessor in Ruby?

In Ruby, object methods are public by default, while data is private. To access and modify data, we use the attr_reader and attr_writer . attr_accessor is a shortcut method when you need both attr_reader and attr_writer .

What does Attr_reader do in Ruby?

attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.

What is Attr_accessible?

attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.

What is an attribute in Ruby?

Attributes are specific properties of an object. Methods are capabilities of an object. In Ruby all instance variables (attributes) are private by default. It means you don't have access to them outside the scope of the instance itself. The only way to access the attribute is using an accessor method.


2 Answers

Never, unless you have specific need for it. Automatic database-backed accessors are created for you, so you don't need to worry.

Any attr_accessors you do create will change the relevant @attr on the rails object, but this will be lost when the object is destroyed, unless you stick it back in the database. Sometimes you do want this behavior, but it's unusual in a rails app.

Now in ruby, it's a different story, and you end up using these very frequently. But I'd be surprised if you need them in rails---especially initially.

like image 189
Peter Avatar answered Sep 28 '22 07:09

Peter


attr_accessor can be used for values you don't want to store in the database directly and that will only exist for the life of the object (e.g. passwords).

attr_reader can be used as one of several alternatives to doing something like this:

def instance_value   "my value" end 
like image 36
Noah Thorp Avatar answered Sep 28 '22 05:09

Noah Thorp