Search code examples
ruby-on-railsactiverecordactive-record-query

Activerecord: find record by grandparent value


I have the following models:

class GrandParent < ActiveRecord::Base
  has_many :parents
  has_many :children, through: :parents
end

class Parent < ActiveRecord::Base
  has_many :children
  belongs_to :grand_parent
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

I'd like to find all Children where the a child's grand_parent has a value equal to TRUE, but I'm having trouble getting the syntax right. Something like:

Child.where(grand_parent.value: TRUE)

Solution

  • You need to join the models in-between to be able to reference GrandParent so you would have to join Parent first and then filter.

    Child.joins(parent: [:grand_parent]).where('grand_parents.value is TRUE')

    Just to verify though, is value an actual column on the grand_parents table or do you just want to get all the children that have associated grand_parents?

    if so...

    Child.joins(parent: [:grand_parent]) should work

    if you want to get all the children without associated grand_parent objects you can do

    Child.joins(:parent).where('not exists(select 1 from grand_parents where grand_parents.id = parents.grand_parent_id')

    it would be slightly different if there's a join table in between like a grand_parent_parents table

    Child.joins(:parent).where('not exists(select 1 from grand_parent_parents where grand_parent_parents.parent_id = parent.id')