0

What I want to do

My application has Order model and List model. List model is Order's child.

Order has total column.
List has price and quantity columns.

I want to update the total of the Order by adding the subtotals of each lists line together.

What I did

Here is my 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

Here is my order.rb(model)

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

To update total price, I set @order.total_price to @order.total. But as you see, it updated with strong parameter(order_params).
I couldn't resolve how to update with total price.

What should I do?

Environments

  • ruby2.7.2
  • rails6
1
  • What parameters do you have in order_params? May 2, 2021 at 20:50

1 Answer 1

1

There are many ways to do it.

# 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))

Finally the most Rails way is probably to use a before_save on the model

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.