【问题标题】:has_many_association multiple queries making it slowhas_many_association 多个查询使其变慢
【发布时间】:2018-09-04 05:33:54
【问题描述】:

我有 has_many_association 表。例如用户 has_many 订阅。在活动管理员的索引页面上,我显示了多个计算字段,我需要为其调用 user.subscriptions.last。因为我多次调用它。因此,由于这个原因,我们的服务器正在超载。它是在索引页面上处理的,因为它在那里只显示 30 个条目。但是在导出到 CSV 时,我们的服务器会因为多次查询而过载。我为一位用户使用了大约 15 个查询。

这里的问题是我必须检查有效订阅以打印其代码。我也不能将 where 查询放在 scoped_collection 中,因为它只会加载用户的有效订阅数据。那么这个问题怎么解决??????

def scoped_collection
  end_of_association_chain.includes(:subscriptions, :blogs)
end
index do  
  column :email
  column "referrer" do |user|
    subscription = user.subscriptions.valid.first
    subscription.referrers.first.code if subscription
  end
  column "blog_id" do |user|
     user.blog.id if user.blog
  end

end

用户 has_many 订阅和订阅 has_many 推荐人我想要第一个推荐人代码

【问题讨论】:

    标签: ruby-on-rails activeadmin


    【解决方案1】:

    将此行添加到您的 users.rb 文件中

     controller do
          def scoped_collection
            # Method 1  
            super.includes(subscriptions: :referrers) # prevents N+1 queries to your database
            # method 2
            User.includes(subscriptions: :referrers).select("users.*, (SELECT referrers.code from referrers LIMIT 1) as refer_code")
          end
      end
    

    【讨论】:

    • 我已经在使用这段代码 def scoped_collection end_of_association_chain.where(:origin => 1).includes(:subscriptions, :blogs) end
    • 您说您对一个用户使用 15 个查询,减少该查询。请添加users.rb的代码。 ,还添加关联一个 schema.rb 需要
    • 谢谢,你是对的,我再次检查了它正在做的查询。问题是嵌套的 has_many_association。订阅 has_many 推荐人,因此它正在为此执行查询。那么如何跳过这些查询。谢谢
    • 如果您添加文件的实际代码,这对我来说会很容易。及相关协会
    • 我已经添加了部分代码.. 现在您可以检查是否需要其他任何内容让我知道。谢谢
    【解决方案2】:

    检索所有字段:

    controller do
      def scoped_collection
        Model.all.as_json(include: [:subscriptions,:referrers])
        # prevents N+1 queries to your database
      end
    end
    

    检索一些字段,例如:

    controller do
       def scoped_collection
         Model.all.as_json(include: [:subscriptions => {only: :field1}])                                       
       end
     end
    

    【讨论】:

      【解决方案3】:

      在您的控制器中调用@subscriptions = current_user.subscriptions

      然后在您的视图中根据需要调用@subscriptions.last,并且不会在视图中调用新查询,因为记录已经加载到控制器中。

      【讨论】:

      • 这个问题解决了。现在问题是由于嵌套的 has_many_associations 引起的。订阅 has_many referrers,所以它正在为此执行查询。那么如何跳过这些查询。谢谢
      • 尝试@subscriptions = current_user.subscriptions.includes(:referrers) 如果您通过订阅调用引用者,它不会执行查询,例如。 @subscriptions.last.referrers
      • @haseeb,不需要调用 .all 方法,因为 current_user.subscriptions 会给你同样的。
      • @MohdAnas 是的,你是对的。从我的答案中删除它。
      • 我已经更新了我的问题和代码,我还面临一个问题。
      猜你喜欢
      • 2014-05-27
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多