2013-10-13 78 views
0

例如,假设我有两个型号:ParentChild查找对象

parent.rb

has_many :children 

child.rb

belongs_to :parent 

我想找到所有的父母,其中任一parent.children.last.gender == "boy"parent.volunteer == "yes"

在此先感谢。

回答

0

你必须有“最后一个孩子是男孩”还是“有一个孩子是男孩”的工作? 这将工作后:

Parent.includes(:child).where("children.gender = 'boy' or parents.volunteer = 'yes'") 

对于最后一个孩子是男孩: 下面是你需要在SQL的东西,你也许可以使用find_by_sql得到它的工作或使用Rails语法创建类似的东西等同或阿雷尔。

select p.* from parents p inner join 
(select parent_id, gender from children where id in (select max(id) from children group by parent_id)) c 
on c.parent_id = p.id where p.volunteer = 'Yes' OR c.gender = 'Boy'; 

根据数据库的大小,此查询可能会运行相当昂贵,替代的解决方案可能是最后一个孩子的性别存储在父记录,并更新它的每一个,如果它是一个不同的新的孩子加入时间目前父母的性别。

+0

不幸的是,我需要“最后一个孩子是一个男孩”。这就是为什么我要做这样的决定。 – David

+0

没问题,这只是一个丑陋的查询仍然可能。 – iouri

+0

你是什么丑陋的查询可能是? – David