Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

ruby on rails - How can I overwrite a getter method in an ActiveRecord model?

I'm trying to overwrite a getter method for an ActiveRecord model. I have an attribute called name in the model Category, and I'd like to be able to do something like this:

def name
  name_trans || name
end

If name_trans attribute is not nil, then return it, else return name attribute. How would I do this?

This should then be called normally like this:

@category.name
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Rails Style Guide recommends using self[:attr] over read_attribute(:attr).

You can use it like this:

def name
  name_trans || self[:name]
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...