我想通過創建兩個名爲主題和lesssons的模型來創建has_many_through關係。我需要創建一個連接表,而不是創建一個單獨的模型。期待更好的解決方案。有沒有辦法在has_many_through中實現「連接表」,而不是創建一個單獨的模型
在此先感謝!
我想通過創建兩個名爲主題和lesssons的模型來創建has_many_through關係。我需要創建一個連接表,而不是創建一個單獨的模型。期待更好的解決方案。有沒有辦法在has_many_through中實現「連接表」,而不是創建一個單獨的模型
在此先感謝!
的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_subjects
爲has_many through:
。
雖然has_and_belongs_to_many
略爲簡單和不加入實例化模型實例有一些大的缺點可以節省內存:
你可以很簡單地從has_and_belongs_to_many
去has_many through:
在以後,如果你發現你需要通過這些功能只是重命名錶並創建一個連接模型。
實際上,我需要與has_many一起創建連接表,而不是has_and_belongs_to_many。有沒有解決方法? –
has_many through:也使用連接表。不同之處在於has_many雖然使用模型來表示連接表中的行。所以不,沒有解決方案 - 而是學習框架。 – max
分享到目前爲止所做的工作 –
您好,歡迎來到StackOverflow。請閱讀https://stackoverflow.com/help/how-to-ask –