Permalink
Browse files

Iteration E1: Creating a Smarter Cart

  • Loading branch information...
1 parent d1f215e commit f0befb8da97f95df4e1f54beae7edd39c9c427d1 @horacix committed May 14, 2011
@@ -42,7 +42,7 @@ def edit
def create
@cart = current_cart
product = Product.find(params[:product_id])
- @line_item = @cart.line_items.build(:product => product)
+ @line_item = @cart.add_product(product)
reset_counter
respond_to do |format|
View
@@ -1,4 +1,14 @@
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
+
+ def add_product(product_id)
+ current_item = line_items.find_by_product_id(product_id)
+ if current_item
+ current_item.quantity += 1
+ else
+ current_item = LineItem.build(:product_id => product_id)
+ end
+ current_item
+ end
end
@@ -1,7 +1,7 @@
<h2>Your Pragmatic Cart</h2>
<ul>
<% @cart.line_items.each do |item| %>
- <li><%= item.product.title %></li>
+ <li><%= item.quantity %> &times; <%= item.product.title %></li>
<% end %>
</ul>
@@ -0,0 +1,10 @@
+class AddQuantityToLineItems < ActiveRecord::Migration
+ def self.up
+ add_column :line_items, :quantity, :integer, :default => 1
+ end
+
+ def self.down
+ remove_column :line_items, :quantity
+ end
+end
+
@@ -0,0 +1,26 @@
+class CombineItemsInCart < ActiveRecord::Migration
+ def self.up
+ Cart.all.each do |cart|
+ sums = cart.line_items.group(:product_id).sum(:quantity)
+
+ sums.each do |product_id, quantity|
+ if quantity > 1
+ cart.line_items.where(:product_id => product_id).delete_all
+ cart.line_items.create(:product_id => product_id,
+ :quantity => quantity)
+ end
+ end
+ end
+ end
+
+ def self.down
+ LineItem.where('quantity > 1').each do |line_item|
+ line_item.quantity.times do
+ LineItem.create(:product_id => line_item.product_id,
+ :cart_id => line_item.cart_id)
+ end
+ line_item.destroy
+ end
+ end
+end
+
View
@@ -10,7 +10,7 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20110513014328) do
+ActiveRecord::Schema.define(:version => 20110514033305) do
create_table "carts", :force => true do |t|
t.datetime "created_at"
@@ -22,6 +22,7 @@
t.integer "cart_id"
t.datetime "created_at"
t.datetime "updated_at"
+ t.integer "quantity", :default => 1
end
create_table "products", :force => true do |t|

0 comments on commit f0befb8

Please sign in to comment.