本文介绍了has_many关联状态检查执行N + 1个查询活动管理员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
模型结构:用户拥有许多订阅和博客,订阅具有has_many优惠券。
我已经包含has_many表,但是我需要为每个订阅执行状态检查
因此,如果我在范围集合中执行where查询,则它将使所有用户仅具有有效订阅。那么如何避免N + 1查询并执行状态检查。
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
推荐答案
仅从查询中加载有效的订阅,请检查以下代码
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
这篇关于has_many关联状态检查执行N + 1个查询活动管理员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!