So. I have users and movies. Users have watched some movies and not others. I want to express this relationship something like this:
Note:
- Not sure if it matters; but movies don't have to be connected to a user; they can exist independently (i.e. Movie 1 has no relationship to User 2). Users can also exist independently; they don't have to have watched or unwatched movies (not pictured here, but you get the idea)
- One movie can be watched by one user but unwatched by another (grey vs. black connections)
My initial reaction is that this a has_many :through
relationship, something like:
/models/user.rb:
def User
has_many :movies, :through => :unwatched_movies
has_many :movies, :through => :watched_movies
end
/models/movie.rb:
def Movie
has_many :users, :through => :unwatched_movies
has_many :users, :through => :watched_movies
end
But first of all, that code definitely doesn't work...
I want to be able to query for, say, u.unwatched_movies
(where u
is an instance of User
, which doesn't seem to jive with the above.
I have a feeling this has something to do with :source
or :as
... but I'm feeling a little lost. Am I right in thinking that this is a 3-level hierarchy, where I need models for User
, UnwatchedMovieList
/WatchedMovieList
, and Movie
? This question feels very close but I can't seem to make it work in this context.
Any help on how to write these models and migrations would be super helpful. Thank you!