2017-09-18 49 views

回答

1

has_and_belongs_to_many association是一個多對多的關聯沒有加入模型:

class Subject < ApplicationRecord 
    has_and_belongs_to_many :lessons 
end 

class Lesson < ApplicationRecord 
    has_and_belongs_to_many :subjects 
end 

來生成連接表運行rails g CreateJoinTableLessonsSubjects lessons subjects

class CreateJoinTableLessonsSubjects < ActiveRecord::Migration[5.0] 
    def change 
    create_join_table :lessons, :subjects do |t| 
     # t.index [:lesson_id, :subject_id] 
     # t.index [:subject_id, :lesson_id] 
    end 
    end 
end 

注意,相比lesson_subjects表命名爲不同的lessons_subjectshas_many through:

雖然has_and_belongs_to_many略爲簡單和不加入實例化模型實例有一些大的缺點可以節省內存:

  • 沒有什麼好辦法來直接查詢連接表。
  • 沒有辦法訪問的連接表附加列描述之間的關係的& B.

你可以很簡單地從has_and_belongs_to_manyhas_many through:在以後,如果你發現你需要通過這些功能只是重命名錶並創建一個連接模型。

+0

實際上,我需要與has_many一起創建連接表,而不是has_and_belongs_to_many。有沒有解決方法? –

+0

has_many through:也使用連接表。不同之處在於has_many雖然使用模型來表示連接表中的行。所以不,沒有解決方案 - 而是學習框架。 – max

相關問題