views:

18

answers:

1

Hello all,

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 thought 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!

+1  A: 

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
j.
ActiveRecord's implementation of #user_defined_title is to call #read_attribute. You're just bypassing that. Note that in forms, the user_defined_title field will have the value defined in predefined_title.
François Beausoleil
I guess this is one bad thing about programming too late. I knew about the read_attribute and in fact tried it. But it still gave me that infinite, loop, looking at your answer, I gave it another try, and it looped again, I couldn't believe that the two of you can be wrong, I looked more carefully to see that the attribute name MUST be a symbol. And that solved everything. Thank You!
Nik
heheh it happens! :]
j.