【问题标题】:How to save product's id to a column of user model如何将产品的 id 保存到用户模型的列中
【发布时间】:2016-06-07 21:56:13
【问题描述】:

所以我在我的 rails 应用程序中构建了一个产品系统和一个购物车。我的目标是将购物车中保存的产品与用户模型相关联。

我正在努力寻找一个解决方案,如何将每个 current_user 的购物车中的商品 ID 保存到用户模型的列中?

因此,在我的购物车视图页面中,有一个购物车中所有已添加产品的列表,我想添加一个保存按钮,该按钮将通过它们的 id 保存这些产品。 例如,如果 current_user 在购物车中添加了 id 为 1、2、3 的三个产品并点击了购物车中的“保存”按钮,我希望能够将这三个 id 按整数保存到当前用户。 这是我的 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 

这有可能实现吗?

(如果有帮助,我正在使用标准的 Devise 设置)

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 shopping-cart


    【解决方案1】:

    您希望如何将多个项目保存到单个列“addedproducts”?我认为最好的解决方案是在购物车中添加外键。使购物车属于用户。并且用户有很多购物车。就像您可能已经创建了一个 Cart 模型和一个 Item 模型一样。在两者之间建立适当的关系...(如果这样做,您将必须向购物车模型添加一个新的迁移并引用用户。)

    【讨论】:

    • 谢谢!好的,但是如果我想在用户模型的不同列中保存三个项目怎么办?
    猜你喜欢
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 2017-07-28
    • 2012-09-29
    • 2011-01-14
    • 1970-01-01
    相关资源
    最近更新 更多