views:

349

answers:

2

In rails we can access db column through attributes rails provided, but can we change this ? for example I have db with name column could I implement something like.

def name
  "sir" + name
end

I tried it, but it result in stack overflow. There is a way to accomplish this.

more question, Is there any difference between name and self.name.

+3  A: 
def name
  "sir" + read_attribute(:name)
end

But avoid this practice. Use an additional getter/setter instead, also known as "virtual attribute". For more information read this answer: http://stackoverflow.com/questions/1144039/decorating-an-attribute-in-rails/1144082#1144082

In your case, there's also a weird side effect. Each time the attribute is accessed, it appends the name. After 3 calls, you end up with

"sir sir sir name"

Indeed, you can do

def name
  n = read_attribute(:name)
  if /^sir/.match(name)
    n
  else
    "sir #{n}"
  end
end

but, seriously, don't do this.

Simone Carletti
I agree that adding a formatted_name method is the way to go, per the link. Don't mess with the attribute name, it's not worth it.
MattMcKnight
A: 

If you're aware of the possible complications, but still need to do this, then:

def name
  "sir" + self[:name]
end
Jeff Schuil
does self[:name] and read_attributes[:name] difference?
art
it is just short hand, see "Overwriting default accessors" at http://api.rubyonrails.org/classes/ActiveRecord/Base.html
Jeff Schuil