Hey guys, I’m at a deadlock here after thinking about this for too long.
Context: Given the following models:
- User
- Item
- Lock
Here’s the scenario: A lock is basically like a ‘hold’. A user can place a ‘lock’ on any given item to signal to the system that the item should not be deleted. Items wont be deleted until the lock is cleared.
Here’s the tricky part. The lock is its own model because I want multiple users to be able to lock any given item. So let’s say Bob locks an item, one didn’t already exist so it creates a lock for that item, and information stating that Bob is currently associated with that lock. John comes and locks the same item, but a lock already exists, so John is simply ‘added under’ the same lock. The lock won’t be removed until all users choose to ‘unlock’, or disassociate themselves with that lock.
My confusion is how I should model these relationships. A user can of course have many locks, each associated with a different item (since any given item can have at most one lock). The locks themselves can have many users. From the point of view of the item, each item can have one lock associated with many users.
So in other words, I would like to access the information a little something like this:
item.lock.users # get the users 'locking' the item
user.locks # get the items the user is currently 'locking
Perhaps the separate Lock model isn’t required, but I figured it would be in order to signify that multiple users can be locking a particular item.
I think what further complicates things is that items are added by users, so I would want to have a way to access the items by a user for example user.items or item.user.
Right now I have:
- user has and belongs to many locks
- lock has and belongs to many users
- user has many items
- item belongs to user
- item has one lock
- lock belongs to item
Does this seem correct?
I think what you’re doing will work though you may not have to use the habtm. What if an item can have many locks and can only be deleted when it has no locks. That way you could add a date/reason/comment for each lock by user.
This will still allow you to do
user.locksthoughitem.lock.userswon’t work, but by looking at each lock you’ll easily be able to get the users.