Rails number_field with Ajax

Viewed 175

I have a form having multiple fields representing an order item. I'm trying to make sure that changes made to quantity of item are saved in real time. I was able to do this when the order item is completely removed through a link_to field. I'm not able to do the same for a number_field:

My code for the 2 fields is as follows:

<%= order_item_form.number_field :quantity, update_quantity_path(:order_item_id => order_item.id, :quantity => order_item.quantity), remote: true, method: :patch, class: "form-control", min: 0 %>
<%= link_to 'Remove', update_quantity_path(:order_item_id => order_item.id, :quantity => 0), remote: true, method: :patch, class: "remove_fields" %>

So in the above, the link_to is working. When the order item is removed, the behavior is correct. For the number_field though, I'm getting an error wrong number of arguments (given 3, expected 1..2)

What am I doing wrong? How can I make the number_field work remotely with Ajax?

2 Answers

The error comes because you are setting a path as one of the arguments to the number_field method.

The documentation tells us that there should only be 2 arguments when we use the method in form builders.

Example: number_field(method, options = {})

Rails API Doc: Link to number_field method

You should use this type of arguments in data:

Example:

<%= order_item_form.number_field :quantity, data: { url: update_quantity_path(...), ... }, ... %>

That eliminates the error.

The rails-way to do this is to add these data attributes to your number_field:

<%= order_item_form.number_field :quantity, class: "form-control", min: 0, data: { remote: true, method: :patch, url: update_quantity_path(order_item_id: order_item.id, quantity: 0) } %>

Have a look at Customize remote elements section in the Working with Javascript in Rails guide for further explanation and to learn how to disable the input field until the Ajax request returns.

Related