Rails 3 - has_and_belongs_to_many

前端 未结 3 644
梦谈多话
梦谈多话 2021-01-25 06:34

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

It looks like i

3条回答
  •  孤独总比滥情好
    2021-01-25 07:18

    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
    

提交回复
热议问题