Justin
Justin

Reputation: 1956

Rails 3 User Database Design Problem - Single Table Inheritance or?

I am working on a peer lending application that has several types of users (ie. borrowers, lenders, sponsors, etc) that have different fields. Moreover, some of these users can belong to two things (ie. lenders can also be sponsors). So, is single table inheritance a good idea in this instance? And if so, can one user belong to two groups with only one "type" field? And if STI is not the way to go, what's the best way to do it? After all, using different tables will require saving the same info to multiple databases, which doesn't seem efficient.

Thanks in advance for any help!!

Upvotes: 1

Views: 416

Answers (2)

Pete Hamilton
Pete Hamilton

Reputation: 7900

You could use the gem I have been working on (CITIER) - http://peterhamilton.github.com/citier to do your inheritance, still in development but currently functioning fine. Much nicer than STI if the different classes have lots of unique fields. STI would leave them Null. Plus MTI is more extensible later down the line. I agree you also need to introduce a role for the users. But I think using this you could link it to the parent (User class) so it would apply to all subtypes of user.

class User < ActiveRecord::Base
   has_many :roles
end

class Role < ActiveRecord::Base
   acts_as_citier
   has_many :users
end

class Borrower < Role
   acts_as_citier
   #Other borrower stuff
end

class Lender < Role
   acts_as_citier
   #Other lender stuff
end

etc

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115721

I think it's safe to assume that a role of each user is determined by the type of a lease/deal. That is, if we have a deal D1 and two users U1 and U2, then it is the deal that defines whether U1 is a sponsor or a borrower.

What I suggest is to leave users hierarchy as an STI and introduce another class, say DealUserRole (Deal, User, Role).

Upvotes: 1

Related Questions