首页 > 解决方案 > Eager load 和 has_many 通过关联

问题描述

在我的模型中,我有这个

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

我想为 event#show 创建一个表,其中包含与该事件关联的用户及其参与状态。

在事件视图中我有这个

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

但是,这会导致 n+1 个查询。如何为@event 预加载用户和参与以消除它们?

我努力了

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

但它没有做这项工作......

标签: ruby-on-railshas-many-througheager-loading

解决方案


在你的 event_controller 你可以像下面这样搜索

@event = Event.includes(participations: :user).find(params[:id])

推荐阅读