2011-09-30 31 views
18

假設我有兩個數據庫:一個用於學生,一個用於課程。我希望能夠爲特定的學生「添加」課程,並且能夠將學生添加到特定的課程中。我假設我需要在這裏使用連接表,但是我對如何使用它們有點遺憾。我想最終希望能夠做一些事情,如:在rails上使用連接表

@class.students.find(@student_id) 

,這將告訴我,如果學生在課堂上或沒有。我知道班級和學生之間的關係是'has_many',反之亦然。在遷移文件中做't.references:學生'是否完成了這個任務?我嘗試將該行添加到我的遷移文件中,然後嘗試使用上面的語句找到某些內容,並且它給了我一個錯誤。我是RoR的新手,所以我甚至不確定實現這個目標的最佳方式是什麼。任何幫助表示讚賞!

回答

12

是的,這是一個多對多的關係(班級有很多學生,學生有很多班級)。爲此,您將使用has_many :through關係。看看ActiveRecord::Associations的文檔(Ctrl-F代表「關聯連接模型」)。

在遷移中,t.references :students是您如何指定belongs_to的關係,因爲它只添加了一個student_id列(它只能容納一個id,即一個學生)。但是,加入模式將包含兩列:student_idclass_id。 (順便說一句,呼籲在Ruby中的模型「類」是自找麻煩我可以建議「課程」。?)

+0

您可以發佈您的學生,班級和加入模型的代碼? –

55

一切真實什麼@Jordan說,這裏具體要採取的步驟:

  1. 創建migrationrails g model CourseStudent爲n:m關係創建聯接模型,並遷移到相應的表。
  2. 編輯遷移文件CreateCourseStudent所以它包含以下內容:

    class CreateCourseStudent < ActiveRecord::Migration 
        def change 
        create_table :course_students do |t| 
    
         # Your code comes here 
         t.integer :student_id 
         t.integer :course_id 
    
         # Here comes the generated code 
         t.timestamps 
        end 
        end 
    end 
    
  3. 運行遷移:rake db:migrate。因此,連接表現在應該存在於數據庫中。

  4. 添加到模型下面的代碼

    class Course < ActiveRecord::Base 
        has_many :course_students 
        has_many :students, :through => :course_students 
    end 
    
    class Student < ActiveRecord::Base 
        has_many :course_students 
        has_many :courses, :through => :course_students 
    end 
    
    class CourseStudent < ActiveRecord::Base 
        belongs_to :student 
        belongs_to :course 
    end 
    

您現在可以使用由方法belongs_tohas_many產生的方法:

  • @course.students
  • @student.courses

試着在Rails Guides找到所有相關的事實和片段,在那裏你應該找到你需要的所有信息。祝你好運!

+3

CourseStudent belongs_to不應該是一個符號。 – ezis

+0

投票!驚人!幫助過我! – Askar

+0

較新版本的rails使用這個進行遷移: 't.integer:student_id' 't.integer:course_id' –

12

這是一個古老的問題,但爲了防止任何人像我一樣磕磕碰碰,現在可以有關係has_and_belongs_to_many。所以,是的,你可以創建一個連接表:

create_join_table :students, :courses do |t| 
    t.integer :student_id 
    t.integer :course_id 
end 

然後在模型中,你會說,有個學生has_and_belongs_to_many :courses 和課程has_and_belongs_to_many :students。沒有必要創建一個名爲CourseStudent的第三課程。這link包含所有此信息

+7

實際上'create_join_table'會爲您自動創建兩個id字段...您可以使用該塊其他領域或索引 – AlexChaffee