如何跨关联创建单个查询



我有一个user模型,它有一个profile,也有一个goal。该profile有一个 hstore 类型的隐私字段,在该字段中可以有一个哈希,指示可以公开显示goal,如果可以显示goal,哈希看起来像 { 'show_goals' => '1' }。我想要一个可以公开显示的所有目标的列表。 我最初的尝试是

def list_public
profiles = Profile.includes(:user).where("privacy @> hstore('show_goals','1')")
goals = []
profiles.each do |p|
goals << p.user.goals.first
end
goals
end
end

当有少数用户选择允许显示他们的目标时,这工作正常,但显然无法扩展。 是否有单个或几个ActiveRecordsql 查询可以完成此代码的工作?我正在使用ruby on rails 5.1.

最简单的方法是在查询中预先加载goals

profiles = Profile.includes(:user, user: :goals).where("privacy @> hstore('show_goals','1')")

这将生成一个额外的查询来获取所有目标。然后,您仍然可以按原样使用剩余的代码,p.user.goals.first不会生成其他数据库查询。

最新更新