I have the following structure:
class User < ActiveRecord::Base
end
class Item < ActiveRecord::Base
end
class Group < ActiveRecord::Base
end
A User can create (and thereby own) a Group.
A Group is a list of Items and a list of the Users who can access these items.
In other words, a user has a list of Items and can control which Users can see these items through the Group membership.
How should I set up the relationship?
Well, you’re going to run into some issues with the fact that you want a double many-to-many relationship here. Ie. groups have and belong to many items, and items have and belong to many users.
So, I would setup the relationship this way, assuming you want a group to be able to have many items, and items may belong to more than one group:
Your migrations will need to look like so:
Now, the structure you’re looking at isn’t the cleanest in the universe, but it will behave as you expect as long as you’re careful about the user association.
For instance, to create a user’s item:
To assign users as able to view an item…
Now, this sets up the relationships you want, but you’ll have to also write your own controller / view logic to limit access, or use a library like CanCan.
For instance:
I hope those examples point you in the right direction. You’ll have a number of issues to deal with relating to access control, but trying to think of them and solve each one I can think of is beyond the scope of this question.
Also, note that this is the simplest setup I could think of. If you have more complex logic in the associations you might want to make a full-fledged join model and use has_many :through associations instead of HABTM.
Good luck!