【发布时间】:2017-01-14 03:34:23
【问题描述】:
我有这些模型,我正在使用带有嵌套属性的茧:
模型/report.rb:
class Report < ApplicationRecord
has_many :option_students
accepts_nested_attributes_for :option_students, allow_destroy: true
end
models/option_students.rb:
class OptionStudent < ApplicationRecord
belongs_to :student
belongs_to :option
belongs_to :report
end
我正在尝试使用 rails 控制台创建报告。我已经在 DB 上保存了一个学生和一个选项。
如果我写:
Report.create(option_students_attributes: [{student_id: 1, option_id: 1}])
控制台输出回滚:
(0.2ms) BEGIN
Student Load (0.2ms) SELECT "students".* FROM "students" WHERE "students"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
Option Load (0.1ms) SELECT "options".* FROM "options" WHERE "options"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.2ms) ROLLBACK
它不会创建报告,也不会创建 option_student 对象。
但是如果我只是输入Report.create 然后我写
Report.update(1, option_students_attributes: [{student_id: 1, option_id: 1}])
更新报告时成功创建选项student。我做错了什么?我只是将嵌套属性与其他模型一起使用,它确实有效。
【问题讨论】:
标签: ruby-on-rails nested-attributes rails-console cocoon-gem