Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read attribute only if it is present?

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.

like image 669
Tintin81 Avatar asked Jan 22 '26 22:01

Tintin81


2 Answers

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.

like image 110
Logan Serman Avatar answered Jan 25 '26 15:01

Logan Serman


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.

like image 34
Ishank Gupta Avatar answered Jan 25 '26 14:01

Ishank Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!