开发者

avoid loop in returning the same attribute in the definition of the method

开发者 https://www.devze.com 2023-01-07 07:06 出处:网络
I have a simple article model with a predefined_title attribute and a user_defined_title attribute All I want is to make a virtual attribute that shows the user_defined_title if available and predefin

I have a simple article model with a predefined_title attribute and a user_defined_title attribute All I want is to make a virtual attribute that shows the user_defined_title if available and predefined_title if not But I 开发者_如何学Gothought what a waste to add another virtual attribute, if I could only do something like this

def user_defined_title user_defined_title || predefined_title end

but then it goes into infinite loop. Is there any way to avoid this?

Thanks!


I can't explain yet why the following works, but it does:

def user_defined_title
   #self[:user_defined_title] || self[:predefined_title] 
   #or
   read_attribute(:user_defined_title) || read_attribute(:predefined_title)
end
0

精彩评论

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