【问题标题】:How to create a single query across associations如何跨关联创建单个查询
【发布时间】:2018-08-14 10:22:37
【问题描述】:

我有一个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

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      相关资源
      最近更新 更多