1

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.

Samuel D.
  • 199
  • 10
  • How do you call the controller function (e.g. which URL do you give)? The format to use is determined by the header and/ore "ending" where no ending defaults to HTML. tl;dr: Try to call it with `.js` at the end of the url. – Cpt.Hook Nov 29 '22 at 22:27
  • @Cpt.Hook i missed the javascript_include_tag 'application', but thank you for your helped me – Samuel D. Nov 29 '22 at 23:08

1 Answers1

1

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

markets
  • 6,709
  • 1
  • 38
  • 48
  • I'm sure and you are right, I missed the <%= javascript_include_tag 'application' %> and add jquery to worked me. Thanks very much for your answer. – Samuel D. Nov 29 '22 at 23:06