Associating Models with Polymorphic

Posted by Josh Crowder on Stack Overflow See other posts from Stack Overflow or by Josh Crowder
Published on 2010-05-24T10:24:10Z Indexed on 2010/05/24 10:31 UTC
Read the original article Hit count: 288

I am trying to associate Contacts with Classes but as two different types. Current_classes and Interested_classes.

I know I need to enable polymorphic but I am not sure as to where it needs to be enabled.

This is what I have at the moment

class CreateClasses < ActiveRecord::Migration
  def self.up
    create_table :classes do |t|
      t.string :class_type
      t.string :class_name
      t.string :date

      t.timestamps
    end
  end

  def self.down
    drop_table :classes
  end
end

class CreateContactsInterestedClassesJoin < ActiveRecord::Migration
  def self.up
    create_table 'contacts_interested_classes', :id => false do |t|
      t.column 'class_id', :integer
      t.column 'contact_id', :integer
    end
  end

  def self.down
    drop_table 'contacts_interested_classes'
  end
end

class CreateContactsCurrentClassesJoin < ActiveRecord::Migration
  def self.up
    create_table 'contacts_current_classes', :id => false do |t|
      t.column 'class_id', :integer
      t.column 'contact_id', :integer
    end
  end

  def self.down
    drop_table 'contacts_current_classes'
  end
end

And then inside of my Contacts Model I want to have something like this.

class Contact < ActiveRecord::Base
  has_and_belongs_to_many :classes, :join_table => "contacts_interested_classes", :foreign_key => "class_id" :as => 'interested_classes'
  has_and_belongs_to_many :classes, :join_table => "contacts_current_classes", :foreign_key => "class_id" :as => 'current_classes'
end

What am I doing wrong?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about polymorphic-associations