mercredi 28 octobre 2015

Show errors and stop form submission for nested forms

I have two models:

Order

OrderLineItem

I do not want to allow negative values to be entered into a nested form for order_line_items. That part is easy enough. The problem is when the form for orders gets submitted with a negative value the nested order_line_item form will also be submitted and fail in the order_line_item controller (as it should) silently and the order form will submit with the success flash message because in the order controller the order form was valid.

How do I get the submission to stop at the order_line_item failure show the flash error and not let the order submit?

order.rb

...
 accepts_nested_attributes_for :order_line_items
...

order_line_item.rb

...
validates :quantity, numericality: { greater_than_or_equal_to: 0 }
...

orders_controller.rb

  def approve
    authorize!(:edit, :order)

    if @order_editable
      #do stuff
      flash[:notice] = "success"
    end
    redirect_to root_url
  end

order_line_items_controller

  def update
    if order_line_item_quantity >= 0
      #do stuff
    else
      flash[:error] = 'Error: Order line item cannot be a negative value'
      respond_with  @oli, error: flash[:error]
    end
  end

Aucun commentaire:

Enregistrer un commentaire