I am trying to display a model attribute only if it is present. If it is not, then a placeholder should be displayed. This is what I've got:
class Person < ActiveRecord::Base
def name
if self.name.blank?
"[You have no name yet]"
else
read_attribute(:name)
end
end
end
However, I am getting a stack level too deep error.
How can this be done?
Thanks for any help.
I agree with Ishank but you can call super to use Rails' getter and then use ActiveSupport's presence method which will return the value if it is present? or otherwise return nil (which will trigger the statement after the ||).
def name
super.presence || "[You have no name yet]"
end
To be clear, stack level too deep is happening because you are checking self.name.blank? - when you use self.name here, that is calling the name method on self (which is the method you are currently in) - so that results in an infinite loop.
This should not be a part of Model. You should write this method in your views.
You can have something like @person.name || "You have no name yet"
You are getting exception stack level too deep because read_attribute[:name] again calls the name method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With