Nested Attributes 嵌套属性

提供类方法 accepts_nested_attributes_for(*attr_names)

attr_names 由:一个或多个属性(association_name) 和 一个或多个可选参数(option)组成。

只接受 options:

:allow_destroy
:reject_if
:limit
:update_only

:limit 在单个 record 构建时不执行;指量构建时,在校验之前执行,并且超过限制的话直接抛错误。实际项目中,不推荐使用。

当你声明嵌套属性时,Rails 会自动帮你定义属性的写方法。

# 摘录部分代码
def #{association_name}_attributes=(attributes)
  assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
end

association_name 就是你声明的属性,例如:

class Book < ActiveRecord::Base
  has_one :author
  has_many :pages

  accepts_nested_attributes_for :author, :pages
end

生成 author_attributes=(attributes)pages_attributes=(attributes)

对于关联对象,会自动设置 :autosave

对于嵌套的属性,默认你可以执行写操作,但不能删除它们。

如果你真的要这么做,也可以通过 :allow_destroy 来设置。如:

上面举例是一对一,下面的一对多关系类似:

自动保存多个嵌套属性,有的可能不符合校验。

为了处理这种情况。你可以设置 :reject_if:

在这里,效果和上面使用 _destroy: '1' 有类似之处。

重现 autosave 创建过程

update_only - 解决更新关联对象时的困扰

之前的写法:

举例:更新关联对象

上述情况,虽然文档上已经写明了。但这违背了我们的直觉,建议加上 :update_only 参数。

之后的写法:

update_only 仅作用于单一关系,对 collection 使用无效。

当然,除上述方法外,还有解决办法就是: 直接获取,然后操作被关联的对象作。或者,直接通过关联对象进行赋值,然后保存(利用 auto_save 进行自动更新)。

invert_of 的另一个作用 accepts_nested_attributes_for with Has-Many-Through Relations

allow_destroy 选项的使用 【Rails】fields_for と accepts_nested_attributes_for 和此方法配套使用的是 fields_for 方法。

最后更新于

这有帮助吗?