Rails 3 - has_and_belongs_to_many

前端 未结 3 645
梦谈多话
梦谈多话 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:10

    In rails 3 the best way is make intermediate table qualification through migration

    the attributes will be like of this table

    subject_id:integer teacher_id:integer

    and also make class of qualification like this

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

    and then define other two models like

     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
    

    and read this link carefully also

       http://blog.hasmanythrough.com/2007/1/15/basic-rails-association-cardinality
    
    0 讨论(0)
  • 2021-01-25 07:16

    You should only use has_and_belongs_to_many if you don't intend to work directly with the join table. In your case, use it if you don't intend to use Qualification itself but only Teacher and Subject and let Active Record do the dirty work. If you have anything to do with the join model, use has_many :through.

    Read more here: Choosing Between has_many :through and has_and_belongs_to_many

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题