Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Rails & ActiveRecord complex query: rendering a collection of has_many through objects while substituting one column

I have a List model. A List has_many :lists_movies and has_many :movies through :lists_movies and has_many :trailers through :movies. ListsMovie has a list_id, movie_id, and title columns.

I want to render all the trailers of movies in a given list, populating all the trailer data AND the list_movie.title. What is the best way to accomplish this?

If I just wanted to render the trailers, I could go:

@trailers = @list.trailers

@trailers.each do |t|
 t.description
 t.youtube_id
end

But I also want the title from the list_movie like:

@trailers.each do |t|
     list_movie.title
     t.description
     t.youtube_id
    end

Basically I'm trying to iterate and get data from 2 different objects.. but having trouble on which collections I should be loading.

Upvotes: 0

Views: 31

Answers (1)

Anand
Anand

Reputation: 3760

Try writing out the query in English: "For each list, I want to write down the list_movie title, and each trailer for that movie", which, in ruby, now easily translates to:

@list.lists_movies.each do |list_movie|
  # list_movie.title
  list_movie.movie.trailers.each do |trailer|
    # trailer.description
    # trailer.youtube_id
  end
end

Upvotes: 1

Related Questions