2016-06-07 452 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

谢谢!好的,但是如果我想从用户模型的不同列中保存三个项目呢? –

相关问题