我有4张像这样的关联表。 - 课程
class Course < ApplicationRecord
has_many :training_frameworks, dependent: :destroy
end
- Training_framework:
class TrainingFramework < ApplicationRecord
belongs_to :course
has_many :training_subjects, dependent: :destroy
has_many :subjects, through: :training_subjects
accepts_nested_attributes_for :training_subjects
end
- Training_subject:
class TrainingSubject < ApplicationRecord
belongs_to :subject
belongs_to :training_framework
end
主题:
class Subject < ApplicationRecord
has_many :training_subjects, dependent: :destroy
has_many :training_frameworks, through: :training_subjects
end
- 在training_framework中,我想通过training_subject创建许多主题。而且我在make param中遇到麻烦并使用它当然要创建training_framwork。 - Param我在rails console中制作和测试:
param = { training_framework: { name: "version1", training_subjects_attributes: [{subject_id: 1}, {subject_id: 2}]}}
=> {:training_framework=>{:name=>"version1", :training_subject_attributes=>[{:subject_id=>1}, {:subject_id=>2}]}}
它与TrainingFramework.create(param[:traning_framework])
而不是@course.training_frameworks.create(param[:traning_framework])
我错在哪里以及如何解决? 搜索与4表关联的关键是什么?
答案 0 :(得分:0)
course
与training_framework
有关。您必须指定要创建course
的{{1}}。
如果你使用强参数,请不要忘记允许参数training_framework
(或course_id
)。
course
param = {
course_id: <course_id>, # <--
training_framework: {
name: "version1",
training_subjects_attributes: [
{subject_id: 1},
{subject_id: 2}
]
}
}
或者您可以先创建TrainingFramework.create(param[:traning_framework])
,然后分配给相应的training_framework
。
检查是否为适当的course
创建了training_framework
:course