Frage

I have this type of relation in my models:

class Movie < ActiveRecord::Base
  has_many :movie_genres
  has_many :genres, through: :movie_genres
end
 
class MovieGenre < ActiveRecord::Base
  belongs_to :movie
  belongs_to :genre
end
 
class Genre < ActiveRecord::Base
  has_many :movie_genres
end

So I am assigning multiple genres to a movie. Also the model MovieGenre has additional columns/attributes like "sort_order" which descripe the order/priority of an genre for a move. So far I can retrieve the genres and I can retrieve the relations (MovieGenre-records) by simply calling @movie.genres or *@movie.movie_genres* but how can I join those two informations and retrieve them together?

So far I saw myself forced to manually search the *movie_genre* record for every genre. Is there a way so that I can get those together so that I have for example the genre.name available together with movie_genre.sort_order?

What would be the rails way or maybe there even exists some rails magic for that?

War es hilfreich?

Lösung

You've got your associations wrong:

class Movie < ActiveRecord::Base
  has_many :movie_genres
  has_many :genres, through: :movie_genres
end

class MovieGenre < ActiveRecord::Base
  belongs_to :movie
  belongs_to :genre
end

class Genre < ActiveRecord::Base
  has_many :movie_genres
  has_many :movies, through: :movie_genres
end

I haven't tested this, but you must use singulars on the through model associations. (And I've added the "has_many :movies" on Genre for symmetry.

And to read the attributes:

@movie.movie_genres.count          # => 3
@movie.movie_genres.first          # => MovieGenre
@movie.movie_genres.first.genre    # => Genre
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top