2016-06-07 456 views
0

因此,我在我的Rails應用程序中構建了一個產品系統和購物車。我的目標是將保存的購物車產品與用戶模型關聯起來。如何將產品ID保存到用戶模型列中

我很努力地找到一個解決方案,我怎樣才能從購物車中的每個current_user節點的id項保存到用戶模型的列?

因此,在我的購物車查看頁面中有一個購物車中添加的所有產品的列表,並且我想添加一個保存按鈕,通過它們的ID保存這些產品。 舉例來說,如果current_user在購物車中用ids 1,2,3廣告三種產品並點擊購物車中的「Save」按鈕,我希望能夠將這三個id通過整數保存到「addedproducts」列中current_user。 這是我cart_controller的一部分:(通過腳手架生成)

def additems 
    id = params[:id] 
    if session[:cart] then 
     cart = session[:cart] 
    else 
     session[:cart] = {} 
     cart = session[:cart] 
    end 
    if cart[id] then 
     cart[id] = cart[id] + 1 
    else 
     cart[id] = 1 
    end 
    redirect_to :action => :index 
    end 

和我的產品控制器的一部分:

class ItemsController < ApplicationController 
    before_action :set_item, only: [:show, :edit, :update, :destroy] 

    respond_to :html, :json, :js 

    def index 
    @products = Product.where(availability: true) 
    end 

    def show 
    end 

    def new 
    @product = Product.new 
    end 

    def edit 
    end 

    def create 
    @product = Item.new(item_params) 
    @product.save 
    respond_with(@product) 
    end 

這是可能實現?

(我使用的是標準制定的設置,如果它的任何幫助)

回答

0

你怎麼想多個項目保存爲單個列「addedproducts」?我認爲最好的解決方案是在購物車中添加外鍵。製作購物車屬於用戶。而用戶有很多推車。就像你可能創建一個Cart模型和一個Item模型一樣。兩者之間的適當關係...(如果你這樣做,你將不得不添加一個新的遷移到參考用戶的購物車模型。)

+0

謝謝!好的,但是如果我想從用戶模型的不同列中保存三個項目呢? –

相關問題