【问题标题】:How to replace an associated collection during ActiveRecord update in Rails?如何在 Rails 中的 ActiveRecord 更新期间替换关联的集合?
【发布时间】:2015-04-24 06:35:04
【问题描述】:

我有以下型号:

class Order < ActiveRecord::Base
  has_many :order_items

  accepts_nested_attributes_for :order_items
end

我想在更新期间完全替换当前的oder_items,而不是添加另一个。

Order.update(
  order.id,
  order_items_attributes: order_items_attributes
)

但这会将新对象添加到order_items,而不是替换它们。该怎么做?

order_items_attributes 例如:

[{"category_id"=>"6e54977c-39e4-402e-93a0-f7a00952ebab", "quantity"=>1}]

【问题讨论】:

  • 先删除所有旧的order_items "order.order_items.delete_all",然后添加新的。
  • 您能把表格寄出吗?
  • 和order_items的内部
  • @crispychicken,已更新
  • @SachinR,看起来很老套;)

标签: ruby-on-rails ruby activerecord rails-api


【解决方案1】:

哈希应该是这样的:

Order.update(
  order.id,
  order_items_attributes: {id: 1, category_id: 123, quantity: 123 }
)

【讨论】:

  • order_items 需要 OrderItem 对象,我传递了一个哈希。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
相关资源
最近更新 更多