新手问题 请问为什么 accepts_nested_attributes_for 在 Rails 5.0.0.1 下不能创建新的关联对象了?

GuiZi · 2016年12月20日 · 最后由 GuiZi 回复于 2016年12月21日 · 1558 次阅读

简单的 model 关系如下:

class Parent < ActiveRecord::Base
  has_one :child
  accepts_nested_attributes_for :child
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

Parent 只有一个 name 字段,Child 有 name 和 parent_id 字段(注:在 rails 5.0.01 下 Parent 和 Child 继续的是 ApplicationRecord)

在 rails 4.2.7 版本下,下面的代码可以保存两个新的关联对象:

params = {parent: {name: 'jack', child_attributes: {name: 'raose'}}}
Parent.create!(params[:parent])

但在 rails5.0.01 下失败了,异常为: ActiveRecord::RecordInvalid: Validation failed: Child parent must exist

不过,如果先创建一个 Parent 对象,再 update 就可以保存 child 到数据库了,如下:

p = Parent.create(name: 'jack0000')
p.update params[:parent]

请问高手,为什么在 5.0.0.1下只能 update,不能 create 了??

#1 楼 @larrylv 非常感谢!

has_one 和 belongs_to 都加上 inverse_of 后就可以了

不过看 sgrif 的回答,好像是个 bug,但还是不太明白原因。@larrylv能解释一下吗?谢谢!!

前两天刚遇到过这个问题,哈哈。也是看了这个 issue 解决的。

@GuiZi 是这个 PR 引入的 bug https://github.com/rails/rails/pull/18937

From changelog:

belongs_to will now trigger a validation error by default if the association is not present. You can turn this off on a per-association basis with optional: true.

但是没有考虑你的这种情况,所以会报 validation error.

GuiZi 关闭了讨论。 12月21日 16:40
7 楼 已删除
需要 登录 后方可回复, 如果你还没有账号请 注册新账号