Question

I have a page in my rails application that requires me to have multiple submit buttons on a single form. To give you an idea of what I am trying to do, I have a shopping cart, which is a table of items. Each item has an order button, and a remove button. There is also a checkbox associated with each item, so that multiple items can be selected, and then submitted for order by a Button at the bottom of my table.

Currently, each of these three buttons have a different "name" property associated with them. In my controller I have code similar to the following:

if params[:remove]
  #do stuff to remove item from shopping cart, then re-direct back to shopping cart
elsif params[:order_one]
  #do stuff to order item, then render a confirm page
else
  #do stuff to order multiple items, then render confirm page
end

But this seems messy to me. Is there a better "railsy" way to implement this?

Also, I am currently not using any JS/Ajax in my pages, and I would like to eventually have the shopping cart be a div that is rendered via Ajax. When a user clicks the remove button, I would like the form to be submitted remotely, so that the shopping cart div can be re-rendered via Ajax once the item is removed from the shopping cart - will this be possible having one form that has a button submitting some forms via ajax, and some forms without ajax?

Was it helpful?

Solution

This is a vast subject, but for an ajax delete button you can start like this. In your table view, use :

<tr id="tr_<%= item.id %>">
  ...
  <%= link_to 'delete', item, method: :delete, remote: true %>
</tr>

You must handle the ajax call on destroy route in your items_controller.rb:

def destroy
  @item= Item.destroy(params[:id])
  respond_to do |format|
    format.html { redirect_to items_url }
    format.js
  end
end

Create a new destroy.js.erb file in your items views folder and put in it :

$('#your_table').remove('#tr_<%= @item.id %>');

Then when you click on the remove button, it will call the destroy action in your controller. As the button is defined as remote, rails will automagically perform an ajax request and won't reload the page. Your controller will render the according js view in which you then remove the row from your table.

As I said, this is only the beginning and it can be done much better on the javascript side. Also note that I didn't check the code.

Also have a look at http://railscasts.com/episodes/136-jquery-ajax-revised?view=asciicast for a more in depth explanation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top