Last active
August 29, 2015 14:11
-
-
Save madeinfree/6f4745c34e42cc201779 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Cart < ActiveRecord::Base | |
has_many :cart_items, :dependent => :destroy | |
has_many :items, :through => :cart_items, :source => :product | |
def add_product_to_cart(product) | |
items << product | |
end | |
def update_quantity_to_cart(product_id, quantity, current_cart_id) | |
## do something.. | |
end | |
# diff | |
#def total_price(cart_id) | |
def total_price #不需要添加(cart_id) | |
#找出這台車有的產品及產品價格(test) | |
#items.each(){ |item| item.price} | |
#找出數量(test) | |
#artItem.where(product_id: 2,cart_id: 5).take!.quantity | |
#運算 | |
#diff | |
#items.inject(0){|sum, item| sum + item.price * CartItem.where("product_id = ? AND cart_id = ?", item.id, cart_id).take!.quantity } | |
items.inject(0) { |sum, item| sum + (item.price * self.cart_items.find_by(:product_id => item.id).quantity) } # 因為此為 current_cart 的方法,所以不用再利用 cart_id 了,這樣會更方便 | |
#note利用.map & 把quantity拆成另一個method | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module CartsHelper | |
def show_cart_total_price(current_cart) | |
#CartItem的quantity*Product的price | |
# diff | |
#current_cart.total_price(current_cart.id) | |
current_cart.total_price #因為已經擁有current_cart了所以就不用再多放 current_cart.id 進去~這是一樣的 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment