0

我有一個名爲add_to_cart的方法,每次用戶將產品添加到購物車時都會調用該方法 - 然後該方法會檢查項目是否已經存在,如果存在,則會增加數量通過+1。放入購物車數量邏輯RoR

我遇到的問題是,如果產品尚不存在於購物車中,我無法確定如何從我的模型中調用我的物品'創建'動作(在物品控制器中)。

我想我可以使用Item.create(...),但我寧願只是調用已在我的項目控制器中存在的創建操作。

目前我有:

產品#索引視圖

... 
<%= button_to "Add to Cart", add_to_cart_path(:product_id => product), :method => :post %> 
... 

路線

... 
post '/add_to_cart/:product_id' => 'carts#add_to_cart', :as => 'add_to_cart' 
... 

車控制器

class CartsController < ApplicationController 

def show 
    @cart = current_cart 
end 

def add_to_cart 
    current_cart.add_item(params[:product_id]) 
    redirect_to cart_path(current_cart.id) 
end 

end 

車型號

class Cart < ActiveRecord::Base 
has_many :items 

def add_item(product_id) 
     item = items.where('product_id = ?', product_id).first 
    if item 
     # increase the quantity of product in cart 
     item.quantity + 1 
     save 
    else 
     save # "THIS IS WHERE I WANT TO CALL ITEMS CONTROLLER CREATE" 
    end 
end 

項目控制器

class ItemsController < ApplicationController 

def create 
    @product = Product.find(params[:product_id]) 
    @item = Item.create!(:cart => current_cart, :product => @product, :quantity => 1, :unit_price => @product.price) 
    redirect_to cart_path(current_cart.id) 
end 

end 

我如何能做到這一點任何幫助重定向到我的創建操作真的非常感謝! :)

+0

我不認爲這是從模型調用控制器中的方法的MVC方法。如果一些邏輯將在控制器之間共享,則邏輯應該在模型中。 「胖模特,瘦削控制器。」 – Yanhao

+0

@顏浩非常感謝您的回覆。你會推薦在模型中使用'Item.create'動作嗎? –

回答

1

您的Cart模型不能調用控制器方法,而不應該需要。

你的方法應該是這樣的:

class Cart < ActiveRecord::Base 
    has_many :items 

    def add_item(product_id) 
    item = items.find_or_create_by_product_id(product_id) 
    item.quantity += 1 
    item.save 
    end 
end 

然後你CartsControlleradd_item方法可以將用戶重定向到他們應該在的位置。