How to get parent data if child data does not exist

Viewed 73

I am trying to get the child data if it exists but when it is nil it will get the parent data.

I don't want to hard code this in the view's because this would require something like:

if @product.parent
  @product.price ? @product.price : @product.parent.price
end

So I thought it would be better to put something in the product model to override that specific attribute like:

# app/models/product.rb
def price
  if self.parent
    self.price ? self.price : self.parent.price
  end
end

But the way above would be ver redundant because i would have to do that for every attribute that model has which would be a lot of functions.

Is there any way to make a function that is going to do the same functionality that would apply to all attributes?

I want to be able to get any attribute from the parent if it is not available from the child

Thanks

1 Answers

you can create a function that looks for the attribute in the object first, if not present, it looks for the attribute in the parent object associatated

  def get_attribute(attr)
    self.send(attr).present? ? self.send(attr) : self.parent.send(attr)
  end

then in the object, you can fetch the attribute using

obj = Model.find(id)
obj.get_attribute(:attr_name)
Related