ruby-on-railsrubyajaxrespond-to

ActionController::UnknownFormat in Rails 5


I have some product list where the user can add/remove items from their product list. I would like the mentioned iteration to be done via ajax with format.js

This is part of my input view where do i have the buttons to add/remove user items from product list:

.input-number__add
  = button_to '', product_add_path(id: product_item), remote: true, class: ''
.input-number__sub
  = button_to '', product_reduce_path(id: product_item), remote: true, class: ''

Here is my method where I add quantity in my item list in ProductItemsController:

  def add_quantity
    @product_item.quantity += 1 # increase 1 to the quantity

    if @product_item.save
      respond_to do |format|
        format.js { render partial: 'product_items/add_quantity' }
      end
    end
  end

What it does is go to 'product_items/add_quantity.js.erb' update the data and answer the request via js, but when it is reading the respond_to format.js I get the error: ActionController::UnknownFormat, highlighting this line: respond_to do |format|

I saw in previous questions that give this solution respond_to :html, :json but this doesn't work for me.

How could I solve this problem?

Thank you for reading me.


Solution

  • Are you sure the route helpers product_add_path and product_reduce_path point to the add_quantity endpoint?

    You can also try forcing the format:

    product_add_path(id: product_item, format: :js)
    

    NOTE Don't forget you need the rails/ujs library in order to use remote: true functionality