dimanche 12 juin 2016

Rails 4 Unprocessable Entity Error when making ajax post

I am trying to build an ajax object and I am getting a funny error...

Here are my nested form fields

<%= f.fields_for :order_item do |ff| %>
    <div class="col-md-4">
        <%= ff.hidden_field :quote_id, value: @quote.id %>
        <%= ff.collection_select :category_id, Category.order(:name), :id, :name, include_blank: "Select Category", hide_label: true %>
    </div>
    <div class="col-md-6">
        <%= ff.grouped_collection_select :product_id, Category.order(:name), :products, :name, :id, :name, include_blank: true, hide_label: true %>
    </div>
    <div class="col-md-2">
        <%= ff.submit "Add Item", class:"btn-u btn-u-blue pull-right", id:"add_item" %>
    </div>
    <% end %>

Here is my quote.js.coffee where I am making my ajax call

$('form').on 'click', '#add_item', (e) ->
e.preventDefault()
product = $('#quote_order_item_product_id :selected').val()
quote = $('#quote_order_item_quote_id').val()
console.log(product)
console.log(quote)
$.ajax '/order_items',
  type: 'POST'
  dataType: 'json'
  data: { product_id: product, quote_id: quote }
  success:(data) ->
    alert data.id
    return false
  error: (jqXHR, textStatus, errorThrown) ->
    alert textStatus
    return false

Here is my controller

def create
@order_item = OrderItem.new
respond_to do |format|
  if @order_item.save
    format.json { render :show, status: :created, location: @order_item }
  else
    format.json { render json: @order_item.errors, status: :unprocessable_entity }
  end
 end
end

I've also tried to make the data being posted in this format

data: { order_item: { product_id: product, quote_id: quote } }

Aucun commentaire:

Enregistrer un commentaire