简体   繁体   中英

Rails avoid N+1 query

Given the following model relationship.

group has_many :members
member has_many :missions
mission has_one :game_set_mission
mission has_one :game_set, :through => :game_set_mission

Here is what I do

Given group is a Group object

# Add a new relationship in member.rb
has_many :game_sets, :through => :missions

# Get all game_set id
group.members.map{ |gc| gc.game_sets.pluck(:id) }

But it seems to occur N+1 query .

How do I improve my code?

Hope following one help you.

GameSet.includes(member: :group)
       .where('groups.id = ?', group.id)
       .pluck('game_sets.id')

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