1

I have a question about doing a query through a few associations using Ruby on Rails.

This question involves querying across three models. (Event, Fight, Fighters). The important parts of the models are as follows:

  • An event has multiple fights.
  • Each fight has two fighters: fighter1 and fighter2.

What I need to write is a function to retrieve a list of all fights that have a given fighter. However, this needs to be done through the Event model due to some weird localization thing we have running.

Is there an easy way to do this?

John Bachir
  • 22,495
  • 29
  • 154
  • 227

1 Answers1

1

Assuming

class Event
  has_many :fights
end

class Fight
  has_many :fighters
end

Then you can do:

events = Event.joins(:fights => :fighters).where("fighters.name = 'sally'")
fights = events.inject([]){|a,e| a = a + e.fights; a }
John Bachir
  • 22,495
  • 29
  • 154
  • 227