11.3 Iteration F3: Highlighting Changes 11.1 Iteration F1: Moving the Cart
Add remote: true to the Add to Cart button
edit app/views/store/index.html.erb
<p id="notice"><%= notice %></p>
<h1>Your Pragmatic Catalog</h1>
<% cache ['store', Product.latest] do %>
<% @products.each do |product| %>
<% cache ['entry', product] do %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
<%= button_to 'Add to Cart', line_items_path(product_id: product),
remote: true %>
</div>
</div>
<% end %>
<% end %>
<% end %>
Enable a the controller to respond to js requests
edit app/controllers/line_items_controller.rb
def create
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to store_url }
format.js
format.json { render :show,
status: :created, location: @line_item }
else
format.html { render :new }
format.json { render json: @line_item.errors,
status: :unprocessable_entity }
end
end
end
Use JavaScript to replace the cart with a new rendering
edit app/views/line_items/create.js.erb
$('#cart').html("<%= escape_javascript render(@cart) %>");
11.3 Iteration F3: Highlighting Changes 11.1 Iteration F1: Moving the Cart