问题
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