ruby-on-rails – 覆盖rails中的嵌套属性

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 覆盖rails中的嵌套属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我在rails中覆盖嵌套属性方法时会发生什么.例如,
class Order
  has_many :line_items
  accepts_nested_attributes_for :line_items

  def line_item_attributes=(attr)
   # what can I do here.
  end
end

class LineItem
  belongs_to :order
end

在上面的代码中,

>里面的line_item_attributes =方法,我可以添加/修改/删除订单的行项吗?
>什么时候是line_items_attributes =被调用,如果我调用@ order.save(params)?

解决方法

>是的,你可以只要打电话

assign_nested_attributes_for_collection_association(:line_items,attributes,mass_assignment_options)

当你完成了

检查源:#文件activerecord / lib / active_record / nested_attributes.rb,第263行

>从文档:

Saving

All changes to models,including the destruction of those marked for
destruction,are saved and destroyed automatically and atomically when
the parent model is saved. This happens inside the transaction
initiated by the parents save method. See
ActiveRecord::AutosaveAssociation.

我不认为覆盖这种方法是个好主意.我将你的代码添加到after_save钩子.

原文链接:https://www.f2er.com/ruby/271631.html

猜你在找的Ruby相关文章