如何跨关联创建单个查询

时间:2018-08-14 10:22:38

标签: sql ruby-on-rails activerecord

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

   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

当少数用户选择允许显示其目标时,此方法很好用,但显然不可缩放。是否有单个或几个ActiveRecord sql查询可以完成此代码的工作?我正在使用ruby on rails 5.1

1 个答案:

答案 0 :(得分:1)

最简单的方法是也渴望在查询中加载goals

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

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