Activerecord: find record by grandparent value

此生再无相见时 提交于 2019-12-07 22:07:24

问题


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)

回答1:


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')



来源:https://stackoverflow.com/questions/35906910/activerecord-find-record-by-grandparent-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!