【发布时间】:2016-04-29 04:40:55
【问题描述】:
我有两个模型,我们称它们为 Parent 和 Child,其中
class Parent < ActiveRecord::Base
has_many :child
end
class Child < ActiveRecord::Base
belongs_to :parent
end
对于一个 API,我有兴趣返回所有匹配特定条件的子对象的列表,以及父 ID 及其对应的父对象(但只有过滤后的子对象的父对象!)而不重复。
类似:
{children: [{id: 1, parent_id: 20, attr1: x, attr2: y},...], parents: [{id: 20, attr3: z, attr4: w},...]}
最有效的方法是什么?
我已经尝试过:
children = Child.eager_load(:parent).where(condition).all
parents = children.map(&:parent).uniq{|p| p.id}
但是使用 map 和 uniq 似乎又慢又浪费?
或者,我可以使用两个 SQL 查询分别查询它们,即
children = Child.where(condition).all
parent_ids = children.map(&:parent_id)
parents = Parent.where(id: parents_ids).all
但是,由于可能有成百上千个不同的父母,这似乎仍然有些低效。
有没有更好的办法?
【问题讨论】:
标签: ruby-on-rails activerecord