9.4 Iteration D4: Hide an Empty Cart 9.2 Iteration D2: Creating an AJAX-Based Cart
edit app/models/cart.rb
class Cart
attr_reader :items # <wtf linkend="wtf.attr.accessor">attr_reader</wtf>
def initialize
@items = []
end
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
current_item = CartItem.new(product)
@items << current_item
end
current_item
end
def total_price
@items.sum { |item| item.price }
end
end
edit app/controllers/store_controller.rb
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@current_item = @cart.add_product(product)
respond_to do |format|
format.js
end
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
edit app/views/store/_cart_item.html.erb
<% if cart_item == @current_item %>
<tr id="current_item">
<% else %>
<tr>
<% end %>
<td><%= cart_item.quantity %>×</td>
<td><%= cart_item.title %></td>
<td class="item-price"><%= number_to_currency(cart_item.price) %></td>
</tr>
edit app/views/store/add_to_cart.js.rjs
page.replace_html("cart", :partial => "cart", :object => @cart)
page[:current_item].visual_effect :highlight,
:startcolor => "#88ff88",
:endcolor => "#114411"
9.4 Iteration D4: Hide an Empty Cart 9.2 Iteration D2: Creating an AJAX-Based Cart