11.4 Iteration F4: Hide an Empty Cart 11.2 Iteration F2: Creating an AJAX-Based Cart
Assign the current item to be the line item in question
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 { @current_item = @line_item }
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
Add the id to the row in question
edit app/views/line_items/_line_item.html.erb
<% if line_item == @current_item %>
<tr class="line-item-highlight">
<% else %>
<tr>
<% end %>
<td class="quantity"><%= line_item.quantity %></td>
<td><%= line_item.product.title %></td>
<td class="price"><%= number_to_currency(line_item.total_price) %></td>
</tr>
Animate the background color of that row
edit app/assets/stylesheets/line_items.scss
// Place all the styles related to the LineItems controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
@keyframes line-item-highlight {
0% {
background: #8f8;
}
100% {
background: none;
}
}
.line-item-highlight {
animation: line-item-highlight 1s;
}
Add an XHR test.
edit test/controllers/line_items_controller_test.rb
test "should create line_item via ajax" do
assert_difference('LineItem.count') do
post line_items_url, params: { product_id: products(:ruby).id },
xhr: true
end
assert_response :success
assert_match /<tr class=\\"line-item-highlight/, @response.body
end
rails test
Run options: --seed 4910
# Running:
...............................
Finished in 0.722340s, 42.9161 runs/s, 92.7541 assertions/s.
31 runs, 67 assertions, 0 failures, 0 errors, 0 skips
11.4 Iteration F4: Hide an Empty Cart 11.2 Iteration F2: Creating an AJAX-Based Cart