0

The question is: how to represent a multiplicity in Ruby on Rails associations? Suppose I have two models - Collection and Item. They are in has_and_belongs_to_many relations. If a collection contains multiple identical instances of items (say, it contains 10 identical items), how should I do this?

I made a try with has_many :through, but it seems to be not very nice approach.

Andrew
  • 2,148
  • 5
  • 23
  • 34

1 Answers1

0

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.

jefflunt
  • 33,527
  • 7
  • 88
  • 126