MongoMapper and "join tables" with properties

154 Views Asked by At

I have lists of items. The items can belong to multiple lists. This is easily done by defining a many to many relation.

class List
  include MongoMapper::Document

  key :item_ids, Array
  many :items, :in => :item_ids
end

But I also want the lists to be ordered. An item can be on index 2 in one list and index 4 in the other. Normally I would use a join table with a 'position' field, but I can't wrap my head around how to accomplish such a thing with MongoMapper, as everyone seems to advise NOT to use join tables in a no SQL environment (which makes perfect sense).

Is it a good idea to use join tables in MongoDB or does it use another mechanic to accomplish this? And bonuspoints: how do I implement this in MongoMapper?

1

There are 1 best solutions below

2
On

item_ids is an array. As such, it's going to be naturally ordered - you can simply insert items into your items association in the order you want them to be in. If you want to re-order them, just sort the item_ids array by some criteria and save the document, or sort the items when you consume them from the array.

# When consuming the list
@list.items.sort_by &:name

# Or if you want to persist the order
@list.item_ids = @list.items.sort {|item| ... }.map(&:id)
@list.save