samedi 9 avril 2022

Ruby on Rails - Generate POST request without refreshing the page

I am creating an e-commerce website with Ruby on Rails and there is something bothering me.

I have a product card with a link. If the user clicks the link, the product goes into the cart. I used remote: true so that it allows to generate the POST request without refreshing the page:

<%= link_to order_items_path(product_id: product), remote: true, method: :post do %>
      <i class="fas fa-shopping-cart"></i>
    <% end %>

But it always ends up refreshing the page and scrolling to the top of the page. Am I missing something?

And if it is not like this how it works, how could I make it do what I want?

Just for reference, the link goes to the OrderItemsController#create:

def create
        @order = OrderItem.generate_order(current_user)
        if order_items_params
            @order_item = OrderItem.new(order_items_params)
        else
            @order_item = OrderItem.new(quantity: 1, product_id: params[:product_id])
        end
        @order_item.order = @order
        authorize @order_item
        if @order_item.save
            redirect_to edit_order_path(@order)
        else
            redirect_to root_path, notice: "Product not ordered, please try again"
        end
    end

Thanks!

Aucun commentaire:

Enregistrer un commentaire