ruby-on-rails - 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| %>
但它没有做这项工作......
解决方案
在你的 event_controller 你可以像下面这样搜索
@event = Event.includes(participations: :user).find(params[:id])
推荐阅读
- c - 如何使用奇异容器在集群上运行 Kaldi 的 Timit 配方?
- c# - 如何覆盖 Bloomberg API RefData
- python - x 轴范围的条形图
- sinon - 用于 AWS X-Ray 调用的 Sinon Stub
- excel - 如何以相反的顺序为一组两个文本代码块创建公共匹配文本字符串
- java - Java Regex 匹配有效的证书格式
- elasticsearch - Elasticsearch docker 文件中的 ${source_elasticsearch} 是什么
- arrays - 当我想对数组进行排序时,初始化后数组已经填充
- laravel - 为分页添加参数
- javascript - 如何通过 JavaScript 找出特定插件在 WordPress 中是否处于活动状态?