has_many association sate check executing N+1 queries active admin

旧巷老猫 提交于 2019-12-13 02:49:39

问题


Model Strucure: User has many subscriptions and blogs , Subscriptions has_many coupons. I have included the has_many table but i need to perform state check for every subscription So if i perform where query in scoped collection than it gets all the user only having valid subscriptions. So how to avoid N+1 query and also perform state check.

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

回答1:


Load valid subscriptions from query only, please check below code

 controller do
      def scoped_collection
        User.includes(subscriptions: :referrers).select("users.*, (SELECT referrers.code from referrers WHERE subscriptions.state = 1 LIMIT 1) as refer_code")
      end
  end


来源:https://stackoverflow.com/questions/52178885/has-many-association-sate-check-executing-n1-queries-active-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!