How to add a property to a Rails 3 model
I have a Book model with two attributes, Title and Subtitle. When subtitle is blank, I want just the title returned, otherwise it should return the both. Is the best, most succinct way to do so, by adding the following to the model?
def full_title
self.subtitle.blank? ? self.title : "#{self.title}: #{self.subtitle}"
end
It do开发者_开发技巧es work, but something seems a bit off, perhaps the abundance of selfs...
you could also make it even a little more succinct and remove the logic:
def full_title
[title, subtitle].compact.join(": ")
end
It'll work with or without the self
def full_title
subtitle.blank? ? title : "#{title}: #{subtitle}"
end
Here's another way to do it but I think yours is more railsy
def full_title
subtitle.blank? ? title : title + ": " + subtitle
end
精彩评论