如何使用强参数更新?

How to update with strong parameter?

我想做什么

我的应用程序有 Order 模型和 List 模型。 List 模型是 Order 的 child.

Ordertotal 列。
Listpricequantity 列。

我想通过将每个 lists 行的小计加在一起来更新 Ordertotal

我做了什么

这是我的 orders_controller.

def update
    @order = Order.find(params[:id])
    @order.total = @order.total_price
    if @order.update(order_params)
      redirect_to orders_path, notice: 'The order has been updated.'
    else
      render :edit
    end
  end

这是我的order.rb(型号)

  def total_price
    lists.to_a.sum { |list| list.subtotal }
  end

为了更新总价,我将 @order.total_price 设置为 @order.total。 但如您所见,它更新了强参数(order_params).
我无法解决如何更新总价。

我该怎么办?

环境

有很多方法可以做到。

# One is just to do it on separate lines.
@order.update(total: @order.total_price)
@order.update(order_params)

# Merge with order_params
@order.update(order_params.merge(total: @order.total_price))

最后最Rails的方法可能是在模型上使用before_save

# Order.rb
before_save do
  total = lists.to_a.sum { |list| list.subtotal }
end

# orders_controller.rb
# just to
@order.update(order_params)