【发布时间】:2017-12-29 16:22:31
【问题描述】:
我正在尝试在 Rails 5 中执行以下查询,当我访问每个 events.contact 时它不会触发 N+1 查询:
events = @company.recipients_events
.where(contacts: { user_id: user_id })
我尝试了一些 .includes、.references 和 .eager_loading 的组合,但都没有奏效。当我访问 events.contact 时,其中一些返回 SQL 错误,而另一些返回 nil 对象。
这是我的联想的简要版本:
class Company
has_many :recipients
has_many :recipients_events, through: :recipients, source: :events
end
class Recipient
belongs_to :contact
has_many :events, as: :eventable
end
class Event
belongs_to :eventable, polymorphic: true
end
class Contact
has_many :recipients
end
实现我需要的正确方法是什么?
【问题讨论】:
-
sn-p 你的看法是什么
-
我正在使用 rails 控制台进行测试
-
你可以尝试使用类似@company.recipients_events.includes(:contact) .where(contacts: { user_id: user_id }) 的东西。并显示错误(如果有)
-
以下是错误:“无法将 'Event' 加入名为 'contact' 的关联;也许你拼错了?”。我相信这是因为 Event 与 Recipient 相关联,Recipient 与 Contact 相关联。
-
我也试过了:@company.recipients_events.includes(flow_recipient: :contact).where(contacts: { user_id: user_id })。在这种情况下,没有错误,但每次我访问 event.contact 时,Rails 都会针对 FlowRecipient load 和 Contact load 执行两个新查询。
标签: ruby-on-rails ruby activerecord associations