2017-08-16 67 views
1

我剛剛開始在rails中使用mongoid進行代碼,之前我使用sql,sqlite等進行了編碼,現在Iam在association之間有點混淆,比如在sql中想要兩個has_and_belongs_to_many之間的關聯你這樣做模特在mongoid中爲has_and_belongs_to_many關係創建一個新表

例如

class Student < ActiveRecord::Base 
     has_and_belongs_to_many :subjects 
    end 

    class Subject < ActiveRecord::Base 
     has_and_belongs_to_many :students 
    end 

,我們創建一個新的表作爲

rails g migration CreateJoinTableStudentSubject student subject 

在我們的遷移文件中,我們做這樣的

def change 
    create_table :students_subjects do |t| 
    t.references :student 
    t.references :subject 
    t.timestamps 
end 

現在我的問題是使用mongoid或DER是做this.plz幫助蔭新mongoid和導軌一個替代方式時,這是neccesary創建一個新表。謝謝

回答

1

你只需要包含一些代碼到你的類是這樣的:

class Student 
    include Mongoid::Document 
    has_and_belongs_to_many :subjects 
end 

class Subject 
    include Mongoid::Document 
    has_and_belongs_to_many :students 
end 

有一個偉大的documentation這裏。

希望它能幫助你!