使用关联搜索 - Ruby rails

Search with associations - Ruby on rails

我有三个关联的 table,我需要通过关联从我的 TransactionSara table 获取所有数据。 我需要我的事件 table 中的所有数据来获取我的 Table 助手中的所有数据,然后从我的 table TransactionSara

中获取所有数据
class Event < ActiveRecord::Base
  has_many :transaction_saras, through: :assistants
end

class Assistant < ActiveRecord::Base  
  has_many :transaction_saras, dependent: :destroy
  belongs_to :event
end

class TransactionSara < ActiveRecord::Base
  belongs_to :assistant
end

我试过用这个解决

Event.all.each do |event|
  event.assistants.transaction_saras
end

但是我得到一个错误:

undefined method `transaction_saras' for 
#<ActiveRecord::Associations::CollectionProxy []>

知道如何执行此搜索吗?

SO 上已经有多个答案,您需要包含关联的模型,以便在遍历它们时可以拥有关联的记录,

Event.includes(assistants: :transaction_saras).all.each do |event|
  p event.assistants # this will be a list of assistants for that event
  p event.assistants.first.transaction_saras.first
end

看看here

您可以在 rails guides

上阅读有关 Activerecord 关联的信息