Forum: Ruby on Rails Polymorphic either or but not both

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
on 2007-02-06 08:27
(Received via mailing list)
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?
Joe C. (Guest)
on 2007-02-06 16:08
(Received via mailing list)
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
Joe C. (Guest)
on 2007-02-06 16:31
(Received via mailing list)
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
Joe C. (Guest)
on 2007-02-06 16:34
(Received via mailing list)
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
This topic is locked and can not be replied to.