lundi 15 octobre 2018

Retain form data on error in json response Rails

I want to retain form data after an error. I can't use render :new due to json response. what should I do here to retain my data. Thanks in advance.

Here is my code in create action.

@invoice = Invoice.new(invoice_params)
total = []
@invoice.line_items.each do |inv|
  total.push(inv.amount.to_i - inv.get_discount)
  if params[:invoice][:pharmacy].present? || inv.category == 'Pharmacy'
    item = Item.find_by_id(inv.item_id)
    if item.present?
      available_item_stock =  item.available_stock
      if available_item_stock.present?
        if available_item_stock.to_i <= 0 || inv.quantity > available_item_stock.to_i
          if inv.category == 'Pharmacy'
            if params[:invoice][:bed_id].present?
              bed = Bed.where(id: params[:invoice][:bed_id]).first
            end
            msg = { :status => "error", :inventory_path => bed_action_admin_beds_path(bed) }
            flash[:notice] = "Invoice couldn't be saved, because #{item.item_name} has no available stock"
            render :json => msg
          else
            msg = { :status => "error", :inventory_path => new_admin_invoice_path(:type => "inventory",:status => "pharmacy") }
            flash[:notice] = "Invoice couldn't be saved, because #{item.item_name} has no available stock"
            render :json => msg
          end
          return
        end
      end
    end
  end

Aucun commentaire:

Enregistrer un commentaire