ruby-on-railsstrong-parameters

How to update with strong parameter?


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


Solution

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