0
class Baby
  belongs_to :child
  attr :is_public
  scope :public, includes(:child).merge(Child.public).where('babies.is_public IS TRUE')
end

class Child
  belongs_to :parent
  attr :is_public

  scope: public, where ???
  def is_public; read_attribute(:is_public).blank? ? self.parent.is_public : super(); end
end

class Parent
  has_many :children
  attr :is_public
end

Is it possible to get a collection of objects of Child where if the value of attribute_a of child is NULL it should get the value from parents.attribute_a in one sql statement

Bogdan
  • 453
  • 4
  • 16

1 Answers1

0

I think, basic SQL logic should by like this:

SELECT c.*,p.* FROM child c
INNER JOIN parent p ON p.id = c.parent_id
LEFT JOIN baby b on b.id = c.baby_id
WHERE b.id IS NULL

if you want to use SQL query instead of ruby class, you can use:

query_result = ActiveRecord::Base.connection.execute('Your query')

Hope this helps

Bukhbayar
  • 31
  • 4