0

After spending a few days of trying to find an answer online, I figured I should ask for help. I'm trying to figure out the best way to implement these relationships using Rails Associations.

I have 4 models: User, Transfer, Building and Bag.

A User has a role attribute. The possible values for role are 'admin', 'building_contact' and 'guest'.

This is what it looks like in a tree structure. The Admin, Guest and BuildingContact is the role of a @user:

           Admin
             |
         Transfer
        /        \
     Guest     Building
       |          |
      Bag     BuildingContact

Therefore:

Admin has_many :transfers
Transfer belongs_to :admin

Transfer has_many :guests
Guest belongs_to :transfer
Guest has_many :bags

Transfer belongs_to :building
Building has_many :transfers
Building has_many :building_contacts

What is the best way to implement the relationship with the User model?

Thanks in advance!

cmoel
  • 148
  • 1
  • 8

1 Answers1

2

One of the fundamental questions that I'd as is:

Will a user have more than one role? I'm guessing not, since you have a single role attribute. They may share many things, but I'd say that the business logic for the different user types would create different models. How about ditching that role attribute and instead using a type attribute and using STI?

class Admin < User; end
class Guest < User; end
class BuildingContact < User; end

That way you will have the inherited User capabilities but you can define differing business logic where appropriate. You can extend this into different controllers and views, otherwise I would think you would risk having a much bigger User class than you would want to.

blackrat
  • 96
  • 5
  • That's perfect! I had that idea last night but didn't know what it was called. So I stayed with the way I was doing it. Thanks for pointing me in the right direction. – cmoel Sep 14 '12 at 00:12