如何将 ID 保存到用户列

How to save ids to users columns

所以我在我的 rails 应用程序中构建了一个产品系统和一个购物车。我的目标是将购物车中保存的产品的 ID 添加到用户模型。因此,在我的购物车视图页面中,有一个购物车中所有已添加产品的列表,我想添加一个保存按钮,该按钮会将这些产品按其 ID 保存到用户 table 的列中。例如,如果 current_user 在购物车中为 ID 为 1、2、3 的三个产品投放广告并点击购物车中的 "Save" 按钮,我希望能够将这三个 ID 按整数保存到三列:product_one、product_two、product_three 之 current_user.

到目前为止,这些是我的模型:

class Item < ActiveRecord::Base
    has_one :cart
end

class User < ActiveRecord::Base

  has_one :cart
  has_many :items, through: :cart 
end

class Cart < ActiveRecord::Base

  belongs_to :user
  belongs_to :item

  validates_uniqueness_of :user, scope: :item
end

我的控制器:

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

  respond_to :html, :json, :js

  def index
    @items = Item.where(availability: true)
  end 

  def show
  end 

  def new 
    @item = Item.new
  end 

  def edit
  end 

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

  def update
    @item.update(item_params)
    flash[:notice] = 'Item was successfully updated.'
    respond_with(@item)
  end 

  def destroy
    @item.destroy
    redirect_to items_url, notice: 'Item was successfully destroyed.'
  end 

  private
    def set_item
      @item = Item.find(params[:id])
    end 

    def item_params
      params.require(:item).permit(:name, :description, :availability) 
    end 
end

我的购物车控制器:

class CartController < ApplicationController

  before_action :authenticate_user!, except: [:index]


  def add
    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


  def clearCart
    session[:cart] = nil
    redirect_to :action => :index
  end






  def index
    if session[:cart] then
      @cart = session[:cart]
    else
      @cart = {}
    end

  end
end

我正在使用 Devise 进行身份验证..

我认为您可能误解了 Rails 关系以及如何使用它们。由于定义关系的方法几乎都是字面意思,因此请仔细查看您的模型并 'read' 它们。

  • 一个项目有一个购物车
  • 一个购物车属于一个项目

一件商品有一个购物车有意义吗?对于购物车来说,拥有一个或多个商品不是更有意义吗?

  • 购物车有一件或多件商品
  • 一件商品属于购物车

然后,您只需将其转化为 rails 方法:

class User < ActiveRecord::Base
  has_one :cart
end

class Cart < ActiveRecord::Base
  belongs_to :user #carts table must have a user_id field
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to :cart #items table must have a cart_id field
end

现在,让我们return 看一下文字。那么,如果我有一个 user 并且想知道他的购物车中有哪些商品,我该怎么做?

  • 我知道一个用户有一个购物车
  • 我知道购物车中有一件或多件商品

因此,要恢复用户购物车中的商品:

user.cart.items

回答您最初的问题,如何将项目保存到 user?你不需要。如果用户有一个 cart 而这个 cartitems 那么,user 会自动有项目(通过 cart 访问它们,如上所述)。