0

I have three tables that are associated, I need to get all the data from my TransactionSara table through the associations. I need all the data in my Event table to get all the data in my Table Assistant and then get all the data from my 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

I tried to solve it with this

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

but I get an error:

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

Any idea how I can do this search?

1 Answers1

0

There are already multiple answers on SO for this, you need to include the associated models so you can have the associated records when you iterate through them,

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

Have a look here

You can read up on Activerecord associations on rails guides

Subash
  • 3,128
  • 6
  • 30
  • 44