【问题标题】:Rollback when creating object with nested attributes创建具有嵌套属性的对象时回滚
【发布时间】: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


    【解决方案1】:

    我假设您使用的是 rails 5,它默认需要更改 belongs_to 关系。理论上保存嵌套属性的时候应该没有问题,但是因为保存的时候还没有设置report-id(实际上是:验证的时候),所以保存会失败。这可以通过告诉 Rails 关联是如何相关的来简单地解决:

    has_many :option_students, inverse_of: :report
    

    或者,您可以在 OptionsStudent 类中添加 optional 选项:

    belongs_to :report, optional: true 
    

    这不太正确,它只会跳过验证,但也许它可能与其他两个关系相关——如果学生或选项并不总是需要的话。

    【讨论】:

    • 谢谢!!只需添加optional: true 即可解决问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多