如何将id保存到用户列

时间:2016-06-08 11:43:07

标签: ruby-on-rails model-view-controller model shopping-cart

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

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

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进行身份验证..

1 个答案:

答案 0 :(得分:2)

我想你可能误解了Rails关系以及如何使用它们。由于定义关系的方法非常直观,因此请仔细查看您的模型并阅读&#39;他们。

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

项目有一个购物车是否有意义?购物车是否更有意义才能拥有一件或几件?

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

然后,您只需将其转换为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

现在,让我们回归文字。所以,如果我有user并想知道他在购物车中有哪些商品,我该怎么办?

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

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

user.cart.items

回答原始问题,如何将商品保存到user?你不需要。如果用户有cart且此cartitems,那么user会自动生成项目(通过cart访问它们,如上所述)。