First I want to clarify that you really want a many-to-many relationship, and not simply a one-to-many where there are duplicate DB records to represent the multiplicity. Because you could, if it's okay, simply duplicate the items
records as many times as necessary and point their collection_id
foreign key to the appropriate Collection
record.
If that's not what you want, and you truly do want a multiplicity, then I wouldn't use ActiveRecord associations to do this. I would simply store an array or list of item_ids
in Collection
objects, and serialize/deserialize this array to a string or text field in the database such that:
collection.item_ids
=> [2, 3, 1, 1, 2, 1, 2, 2, 2, 2, 5, 6, 2, 3, 2]
Where each entry in the item_ids
attribute is a foreign key to the items
table.
If you happen to be using Postgres as your DB I think you can actually store the list/arrays as a Postgres array
column, though I've never actually tried to do this in Rails myself.