2012-03-30 89 views
1

我有2個模特 - 教師主題。 A想通過名稱資格連接表連接它們。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

相信你需要一個模式叫資格映射表。 – 2012-03-30 14:11:11

+0

@NekoNova:只有當ExiRe想要對連接表本身做些什麼的時候,否則,讓AR做一些骯髒的工作。請參閱下面的答案以獲取附加鏈接。 – jipiboily 2012-03-30 15:07:47

回答

3

首先,在遷移中創建表格不會定義您的模型。你必須在app/models/qualification.rb創建Qualification模型:

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

其次,如果你使用Rails 3,扔出去has_and_belongs_to_many和使用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

在軌道3最好的辦法是讓中間通過移民表格資格認證

屬性將如此表

sub 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

我相信你應該在'Qualification'模型中擁有'belongs_to'而不是'has_many'。 – ExiRe 2012-03-30 15:08:48

1

你應該只使用has_and_belongs_to_many,如果你d不打算直接使用連接表。在你的情況下,如果你不打算使用Qualification本身,但只使用Teacher和Subject,並讓Active Record執行骯髒的工作,則使用它。如果您與加入模型有任何關係,請使用has_many:through。

更多在這裏閱讀:Choosing Between has_many :through and has_and_belongs_to_many

+0

感謝您的信息! – ExiRe 2012-03-30 15:04:22

相關問題