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?
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 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.