Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 override a model attribute with parent attribute

What is the best way to achieve the following in Rails 4? Parent and child model have the same attribute. If child model hasn't set said attribute then it inherits from the parent, otherwise, it renders its own value.

I tried to create a method in the child method with the same name as the model attribute to do the logic, but that causes a stack level too deep error.

  def age_of_seniority
    age_of_seniority.present? ? age_of_seniority : borough.age_of_seniority
  end

Update

I don't want to change the method name, I would like to be able to access it as a normal attribute

like image 523
user3868832 Avatar asked Dec 10 '25 00:12

user3868832


1 Answers

You can do this using read_attribute

def age_of_seniority
  read_attribute(:age_of_seniority) || borough.age_of_seniority
end
like image 108
Rajdeep Singh Avatar answered Dec 16 '25 18:12

Rajdeep Singh



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!