Search code examples
ruby-on-railshas-many-througheager-loading

Eager load and has_many through association


In my models I have this

class User< ApplicationRecord
  has_many :participations
  has_many :events, :through => :participations
end

class Event < ApplicationRecord
  has_many :participations
  has_many :users, :through => :participations
end

class Participation < ApplicationRecord   
  belongs_to :user
  belongs_to :event    
end

I would like to create a table for the event#show with the users that are associated with the event and their participation status.

In the event view I have this

<% @event.users.each do |user| %>
   <% p = Participation.find_by user_id: user.id, event_id: @event.id %>
........
.......

However, this results in n+1 queries. How can I preload users and participations for @event to eliminate them?

I have tried

   <% @event.users.includes(:participations).each do |user| %> 

but it does not do the job.....


Solution

  • Instead of fetching all users and iterating them to get their participation and then their associated event, you could first include user and event in participations and then iterate them to get event and user of each participation record:

    Participation.includes(:user, :event).where(event_id: @event.id).each do |participation|
      puts participation.user.id
      puts participation.status
      puts participation.event.id
    end