Activerecord: find record by grandparent value

一笑奈何 提交于 2019-12-06 11:24:49

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

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