I’m wanting to add some AJAX functionality to my Rails app, but have no idea where to start.
Here is the method that adds an item to an order:
def add_item_to_order
if session[:order_id].nil?
@order = Order.new #Don't create an order until there is an item to be added to it.
@order.account_id = session[:user_id]
else
@order = Order.find(session[:order_id])
end
item = Item.find(params[:id])
o_item = OrderItem.new
o_item.item_id = item.id
@order.order_items << o_item
@order.total += item.sale_price
@order.save
session[:order_id] = @order.id
redirect_to order_home_path
end
This is run when the user clicks:
<%= link_to item.name, add_item_to_order_path(item.id), :class => "fixed medium green button"%>
Can anyone give me any tips on how to get started, so the the item is added to the order via AJAX?
Great tutorial, did this myself: http://ruby.railstutorial.org/ruby-on-rails-tutorial-book Chapter 12 has some stuff on Ajax.
Important part is to set your link_to paramater
data-remotetotrue:and in your controller you add
Then you’ll need a .js.erb file to handle the format.js repsonse:
and a partial page file to hold the new data..