# Active record accessor best practices?

**URL:** <https://www.ruby-forum.com/t/active-record-accessor-best-practices/175051>\
**Category:** Rails\
**Created:** [September 7, 2009, 1:37am UTC](https://www.ruby-forum.com/t/active-record-accessor-best-practices/175051 "2009-09-07T01:37:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tony](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/ee7513/32.png) [@tony](https://www.ruby-forum.com/u/tony)\
**Post date:** [September 7, 2009, 1:37am UTC](https://www.ruby-forum.com/t/active-record-accessor-best-practices/175051/1 "2009-09-07T01:37:15Z")

</div>

Within an ActiveRecord sub-class I have seen several ways that people  
access the model attributes. As I have wandered through various  
blogs, my code now uses several different methods and I’m planning on  
making my code consistent but I’m curious what the “best way”  
is. 🙂

If I have a ‘name’ attribute on a model there are at least 4 different  
ways to get it from within the class (@name is not one of them) and at  
least 3 ways to set it. (i suspect there are more but these are what  
I am using.)

Example…  
class CreateAttributes \< ActiveRecord::Migration  
def self.up  
create\_table :attributes do |t|  
t.column :name, :string  
t.timestamps  
end  
end

def self.down  
drop\_table :attributes  
end  
end

class Attribute \< ActiveRecord::Base  
########## Getters ############  
def name\_by\_self\_dot  
self.name or ‘unlisted’  
end  
def name\_by\_self\_bracket  
self[:name] or ‘unlisted’  
end

def name\_by\_read\_attribute  
read\_attribute(:name) or ‘unlisted’  
end

def name\_by\_name  
name or ‘unlisted’ # I assume this is just calling the name  
method  
end

########## Setters ############  
def name\_by\_self\_dot=(txt)  
self.name = txt  
end  
def name\_by\_self\_bracket=(txt)  
self[:name] = txt  
end

def name\_by\_write\_attribute=(txt)  
write\_attribute(:name, txt)  
end

def name\_by\_name=(txt)  
name=txt # THIS DOES NOT WORK. I guess it creates a local  
variable instead of calling the setter.  
end  
end

Anyway. Which one is best? I personally like the self.attribute way  
as it is short and it also works the same if you have an instance  
variable you defined with attr\_accessor. Any thoughts?

Tony
