[英]How to save ids to users columns
因此,我在Rails應用程序中構建了一個產品系統和一個購物車。 我的目標是將購物車中保存的產品的ID添加到用戶模型。 因此,在我的購物車視圖頁面中,有一個購物車中所有已添加產品的列表,我想添加一個保存按鈕,該按鈕會將這些產品的ID保存到users表的列中。 例如,如果current_user在購物車中將三個產品ID為1,2,3的廣告投放並單擊購物車中的“保存”按鈕,我希望能夠將這三個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進行身份驗證。
我認為您可能誤解了Rails關系以及如何使用它們。 由於定義關系的方法幾乎是字面值,因此請仔細查看模型並“讀取”它們。
一件商品有一個購物車有意義嗎? 對一個推車有一個或多個物品不是更有意義嗎?
然后,將其轉換為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
並且此cart
有items
則user
自動擁有商品(如上所述,通過cart
訪問商品)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.