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
<% if notice %>
<aside id="notice"><%= notice %></aside>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<ul class="catalog">
<% cache @products do %>
<% @products.each do |product| %>
<% cache product do %>
<li>
<%= image_tag(product.image_url) %>
<h2><%= product.title %></h2>
<p>
<%= sanitize(product.description) %>
</p>
<div class="price">
<%= number_to_currency(product.price) %>
<%= button_to 'Add to Cart', line_items_path(product_id: product),
remote: true %>
</div>
</li>
<% end %>
<% end %>
<% end %>
</ul>
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 Coffeescript to replace the cart with a new rendering
edit app/views/line_items/create.js.coffee
cart = document.getElementById("cart")
cart.innerHTML = "<%= j render(@cart) %>"
rails test
Run options: --seed 58518
# Running:
..............................
Finished in 0.421901s, 71.1067 runs/s, 149.3241 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