Search code examples
ruby-on-railsrubyactiverecordrails-modelsobject-relationships

How do I get a Rails association to use a certain name to access a model of a different name?


Let's say I have a user model and a movie model as well as tables to store them. Let's say I want to add a watchlist feature by adding a third table called watchlist_movies that simply maps a user_id to a movie_id.

I now want to add a watchlist_movie model. I want to be able to query ActiveRecord with user.watchlist_movies and get a collection of movie objects. So far, I've tried (in user.rb)

has_many :watchlist_movies 

and

has_many :movies, through: watchlist_movies

The first results in user.watchlist_movies returning a record of and the second will return a collection of movie records at user.movies. Essentially what I want is for user.watchlist_movies to return a collection of movie records, so I want the access as defined in the first relationship to return the content of the second relationship. How do I do this?


Solution

  • You're defining the relationships correctly here, but you may have a case of your expectations not aligning with how Rails does things. If your structure is that of Movie being related to User through WatchlistMovie, which is a simple join model, you're on the right track.

    Remember you can call your relationships anything you want:

    has_many :watchlist_movie_associations,
      class_name: 'WatchlistMovie'
    
    has_many :watchlist_movies,
      class_name: 'Movie',
      through: :watchlist_movie_associations
    

    I'd advise against this since it goes against the grain of how ActiveRecord prefers to name things. If it just bugs you right now, that's understandable, but if you embrace the style instead of fighting it you'll have an application that's a lot more consistent and understandable.