I am trying to create a generic person model. Then subclass it as either a professor or an author. The only problem is that since some professors are authors, I don't want duplicate entries. Any ideas on how to handle this?
I wouldn’t use a polymorphic model for this, I would use single table inheritance.
Have a single table People with a type column, then have a model Person and subclasses for each type so:
class Person < ActiveRecord::Base
end
class Professor < Person end
class Author < Person end
I just went back and re-read your original post, single table won't work either since you have the possibility of a person having two types.
The solution is going to be a little more complex as you will need to create a many to many relationship.
I would use 3 tables:
create_table :people do |t| t.column :id, :integer t.column :name, :string end
create_table :person_roles do |t| t.column :id, :integer t.column :person_id, :integer t.column :role_id, :integer end
create_table :people do |t| t.column :id, :integer t.column :role, :string end
"People" would house the information about the person, "Roles" would be a domain of roles a person could play (Author, professor, student), and "Person_Roles" would allow the many to many.
You would then have:
class Person < ActiveRecord::Base has_many :roles, :through => :person_roles has_many :person_roles end
Hope that helps, sorry for my hasty first post!
Joe
I should know never to post prior to my morning caffeine intake… There is a typo on the third table definition:
create_table :people do |t| t.column :id, :integer t.column :role, :string end
Should be: create_table :roles do |t| t.column :id, :integer t.column :role, :string end