2012-03-30 8 views
1

私は2モデルあります - 教師件名です。名前が、資格がの結合表を介してそれらを接続したい。Rails 3 - has_and_belongs_to_many

私は間違って何かやるように見えます:

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 

マイ移行:

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 

私は例

ruby-1.9.3-head :013 > Qualification 

用レールコンソールや印刷を開くと、私はこれを取得します:

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>' 

どうしたのですか?

+0

は、あなたがテーブルにマップモデルと呼ばれる資格が必要と考えています。 –

+0

@NekoNova:ExiReが結合テーブル自体で何かをしたい場合にのみ、そうでなければ、ARが汚い作業をするようにします。添付のリンクについては、私の答えをご覧ください。 – jipiboily

答えて

3

最初に、移行でテーブルを作成しても、モデルは定義されません。あなたはapp/models/qualification.rbQualificationモデルを作成する必要があります。

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

第二に、あなたはRailsの3、has_and_belongs_to_manyを捨てるとhas_many :throughを使用して使用している場合:

レール3に
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

を最善の方法は、中間体を作るです移行

てテーブル資格属性は、この表の

サブのようになりますject_id:整数 teacher_id:整数も

とは、この

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

のような資格のクラスを作成し、その後、

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 

のように、他の二つのモデルを定義し、慎重にも、このリンク

http://blog.hasmanythrough.com/2007/1/15/basic-rails-association-cardinality 
を読みます
+1

私はあなたが '資格'モデルで 'has_many'の代わりに' belongs_to'を持っているべきだと考えています。 – ExiRe

1

あなたはhas_and_belongs_to_manyを使用する必要があります。 joinテーブルで直接作業するつもりはありません。あなたのケースでは、資格そのものを使用するつもりはなく、教師と科目のみを使用し、アクティブレコードに汚れた作業をさせる場合に使用してください。結合モデルと関係がある場合は、has_many:throughを使用します。

もっとここで読む:Choosing Between has_many :through and has_and_belongs_to_many

+0

その情報をありがとう! – ExiRe