开发者

Can I implement rails setter and getter for attributes for db columns

In rails we can access db column through attributes rails provided, 开发者_JAVA技巧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.


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: decorating an attribute in rails

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.


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

def name
  "sir" + self[:name]
end


Use super

Ruby Overriding methods

It has a lot of explaining but I think it is as simple as calling the method that's already defined

def name
  "sir #{super}"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜