Rails - inheritance hierarchy of classes where a subtype can play two roles
I need to model Owners and Rentees in an application, so you have stuff that is always owned by someone and can be rented for someone else. I first approached this problem with Single Table Inheritance because both types of person will share all attributes, so you would have a model called Person associated to a table people with Owner and Rentee inheriting from Person.
The problem is that Single type inheritance discerns subtypes using a field type and therefore a record in the table can represent either an Owner or a Rentee but not both at the same time, while in the real context you can have an Owner which is renting something from another Owner and therefore that person is at the same time an Owner and a Rentee.
How w开发者_运维百科ould you approach this problem? Would you use separated tables for owners and rentees? Is there any other type of table inheritance in Rails?
I would suggest that you keep it simple. You have people who can both rent and own items - same people, same items - just add a way to track who owns and item and who rented it.
You could do something like this:
class Person
has_many :items
has_many :rented_items, :class_name => "Item", :foreign_key => "rentee_id"
end
class Item
belongs_to :person
belongs_to :rentee, :class_name => "Person", :foreign_key => "rentee_id"
end
# so you have:
person.items # all the items a person owns
person.rented_items # all the items he has rented
精彩评论