Search code examples
ruby-on-railsrubymigrationmodel-associations

Rails 3 - has_and_belongs_to_many


I have 2 models - Teacher and Subject. A want to connect them via Join table with name Qualification.

It looks like i do something wrong:

class Teacher < ActiveRecord::Base
  has_and_belongs_to_many :subjects, :join_table => "Qualification"
end

class Subject < ActiveRecord::Base 
  has_and_belongs_to_many :teachers, :join_table => "Qualification"
end

My migration:

class CreateQualificationJoinTable < ActiveRecord::Migration
  def change
    create_table :qualification, :id => false do |t|
      t.integer :subject_id
      t.integer :teacher_id
    end
    add_index :qualification, :subject_id
    add_index :qualification, :teacher_id
  end
end

When i open rails console and print, for example

ruby-1.9.3-head :013 > Qualification

I get this:

NameError: uninitialized constant Qualification
    from (irb):13
    from /Users/serg/.rvm/gems/ruby-1.9.3-head/gems/railties-3.2.0/lib/rails/commands/console.rb:47:in `start'
    from /Users/serg/.rvm/gems/ruby-1.9.3-head/gems/railties-3.2.0/lib/rails/commands/console.rb:8:in `start'
    from /Users/serg/.rvm/gems/ruby-1.9.3-head/gems/railties-3.2.0/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

What is wrong?


Solution

  • First, creating the table in a migration doesn't define your model. You have to create a Qualification model in app/models/qualification.rb:

    class Qualification < ActiveRecord::Base
      belongs_to :subjects
      belongs_to :teachers
    end
    

    Second, if you're using Rails 3, throw out has_and_belongs_to_many and use has_many :through:

    class Teacher < ActiveRecord::Base
      has_many :qualifications
      has_many :subjects, :through => :qualifications
    end
    
    class Subject < ActiveRecord::Base 
      has_many :qualifications
      has_many :teachers, :through => :qualifications
    end