我有父母,孩子,技能的关系。每个父母都可以生几个孩子,每个孩子都有一个技能。
我想从数据库中返回所有的父母,如果他们有一定的技能的话,我想包括属于他们的孩子。
在查询结束时,我们将有几个父母,可能有0个孩子。我正在尝试像这样的Parent.includes(children: [:skill]).where(skill: {skill_type: type}),但这并不能返回所有的父母。通过ActiveRecord可以做到这一点吗?
发布于 2015-11-15 01:22:51
class Parent < ActiveRecord::Base
has_many :children
has_many :skills, through: :children
def self.with_skill(skill_type)
children = Child.joins(:skills).where(skills: { skill_type: skill_type } )
Parent.all.map do |parent|
children = children.select { |c| c.parent_id == parent.id }
# This marks the association as loaded so that rails does not issue a n+1 query
association = parent.association(:children)
association.loaded!
association.target.concat(children)
children.each { |c| association.set_inverse_instance(c) }
parent.readonly! # because we dont want to accidentally set the children to []
parent
end
end
end在这里,我们使用两个查询,第一个查询获取所有具有所选技能和技能的子级。第二个得到了所有的父母。
然后,我们手动设置父级和子级之间的关系,这样它的parent.children就不会导致ActiveRecord查询数据库中的子数据库。
我们还将记录标记为只读记录,因为如果保存了其中一个记录,则可以从关联的子记录中删除parent_id。
总之,这是一个小的工作-周围的工作,将很好地显示记录。Rails并不允许您按照这里所希望的方式准确地选择和选择应该预先加载哪些关联。
https://stackoverflow.com/questions/33714703
复制相似问题