Joshua Delaney
Joshua Delaney

Reputation: 93

Querying through associations with Ruby on Rails

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:

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?

Upvotes: 1

Views: 201

Answers (1)

John Bachir
John Bachir

Reputation: 22731

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 }

Upvotes: 1

Related Questions