Reputation: 620
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
I don't want to change the method name, I would like to be able to access it as a normal attribute
Upvotes: 3
Views: 487
Reputation: 17834
You can do this using read_attribute
def age_of_seniority
read_attribute(:age_of_seniority) || borough.age_of_seniority
end
Upvotes: 3
Reputation: 21439
You are recursively calling the method from within the method, this of course will cause a stack overflow.
def age_of_seniority
age_of_seniority.present? ? age_of_seniority : borough.age_of_seniority
end
If the age_of_seniority is stored in the instance variable, you access it with:
@age_of_seniority
So in your code:
def age_of_seniority
@age_of_seniority.present? ? @age_of_seniority : borough.age_of_seniority
end
And to call the overrided method from parent, you can just use super
.
not quite sure what's borough.age_of_seniority
doing.
Upvotes: 0
Reputation: 9764
Call super:
def seniority_age
super || borough.age_of_seniority
end
A simple example:
class Parent
attr_accessor :seniority_age
end
class Child < Parent
def seniority_age
super||'foo'
end
end
c = Child.new
puts c.seniority_age
c.seniority_age = "bar"
puts c.seniority_age
returns:
foo
bar
Upvotes: 1