Search code examples
javascriptruby-on-railsshopping-cartcartbutton-to

avoid button_to action with javascript in rails


I am making a shopping cart and the user can only add products to the cart when signed in.

I created some JavaScript for when the user clicks the button "Add to cart", it evaluates if someone is signed in and displays a message, but I need to stop the button action because cause a problem for a render action. Thanks. Here is my code

<%=button_to 'Add to cart',line_items_path(:product_id => product.id),:onclick=>"javascript:is_user()"%>

Solution

  • You could try something like this:

    <% if current_user.present? %>
      <%= button_to 'Add to cart',line_items_path(:product_id => product.id) %>
    <% else %>
      <%= button_to 'Login to add to cart', '' %>
    <% end %>