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 @products do %>
<% @products.each do |product| %>
<% cache 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)
respond_to do |format|
if @line_item.save
format.html { redirect_to store_index_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("<%=j render(@cart) %>");
rails test
Run options: --seed 30807
# Running:
..............................
Finished in 0.766449s, 39.1415 runs/s, 82.1972 assertions/s.
30 runs, 63 assertions, 0 failures, 0 errors, 0 skips
11.3 Iteration F3: Highlighting Changes 11.1 Iteration F1: Moving the Cart