I was wondering what the best way to model a relationship where an object is associated with exactly n objects of another class. I want to extend the has_one relationship to a specific value of n.
For example, a TopFiveMoviesList would belong to user and have exactly five movies. I would imagine that the underlying sql table would have fields like movie_id_1, movie_id_2, … movie_id_5.
I know I could do a has_many relationship and limit the number of children at the model level, but I’d rather not have an intermediary table.
My first instinct would be to use a join table, but if that’s not desirable
User.movie[1-5]_idcolumns would fit the bill. (I thinkmovie1_idfits better with Rails convention thanmovie_id_1.)Since you tagged this Rails and ActiveRecord, I’ll add some completely untested and probably somewhat wrong model code to my answer. 🙂
You could wrap that line in a macro-style method, but unless if that’s a common pattern for your application, doing that will probably just make your code that harder to read with little DRY benefit.
You might also want to add validations to ensure that there are no duplicate movies on a user’s list.
Associating your movie class back to your users is similar.
(Of course that
users_list_as_top_anythingwould probably be better written out as explicit SQL. I’m lazy today.)