简体   繁体   中英

Rails joins nested table with condition and prevents N+1 query

The models are simply User and Review . Relationship: User has many Reviews . I want to query out which User has more than 2 reviews.

I wrote this and it works.

User.joins(:reviews).group(:id).having("COUNT('reviews.id') > 2")

Then I want to wrap them and return users' id , first_name and the review's title . Therefore, I've tried the following but throwing out an N+1 query issue.

User.select(:id,:first_name)
    .joins(:reviews).group(:id)
    .having("COUNT('reviews.id') > 2")
    .as_json(include: {reviews: {only: :title}})

Simply replace joins to includes seems not working, is there any way to solve eager loading with group , having condition?

Try this:

User.select(:id, :first_name).left_joins(: reviews).includes(: reviews).group(:id).having("COUNT('reviews.id') > 2")

It works for me, however, I do not what is .as_json(include: {items: {only: :title}}) and if it will works with .as_json(include: {items: {only: :title}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM