Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Rails: how to make elegant calls with has_many through

I have a User model and a Movie model and a MovieRatings model. Users have_many Movies through MovieRatings and vice versa.

A Movie Rating has a user_id, movie_id, and wants_to_see. wants_to_see is a boolean. Is there a simple way to get a user's list of movies where wants_to_see = true?

user.movies.where(wants_to_see: true) gets me a AssociationRelation object. user.movie_ratings.where(wants_to_see: true) gets me a list of of MovieRating objects which I then need to find the associated movie.

What's the best way to achieve this?

Upvotes: 2

Views: 23

Answers (1)

Joe Kennedy
Joe Kennedy

Reputation: 9443

You could achieve this a couple of ways. You could create a function that returns the movies that a user wants to

class User < ActiveRecord::Base
  has_many :movie_ratings
  has_many :movies, through: :movie_ratings

  def wants_to_see_movies
    self.movies.where(movie_ratings: { wants_to_see: true } )
  end
end

Alternatively, you could create an additional association using has_many for the "want to see" movies

class User < ActiveRecord::Base
  has_many :movie_ratings
  has_many :movies, through: :movie_ratings
  has_many :wants_to_see_movies, -> { where(movie_ratings: { wants_to_see: true } ) },
                                 through: :movie_ratings,
                                 source: movie
  end
end

Frankly, I'm not sure which solution is better/more recommended, but in either case, when you want to get all the movies a user wants to see,

@movies = @user.wants_to_see_movies

Upvotes: 1

Related Questions