因此,我在我的Rails應用程序中構建了一個產品系統和一個購物車。我的目標是將購物車中保存的產品的id添加到用戶模型中。因此,在我的購物車視圖頁面中,購物車中包含所有添加產品的列表,並且我想添加一個保存按鈕,通過它們的ID將這些產品保存到用戶表中的列中。舉例來說,如果current_user在購物車中推出了三種產品,並且點擊購物車中的「保存」按鈕,我希望能夠通過整數將這三個ID保存到三列:product_one,product_two ,current_user的product_three。如何將ID保存到用戶列
到目前爲止,這些都是我的模型:
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
而且我使用的設計進行驗證..
很奇怪你的購物車belongs_to:item,不是嗎?手段用戶有一個手推車,並且手推車連接(屬於)只有一個項目。所以用戶只會有一個項目,對嗎?您目前如何設想將多個項目連接到單個用戶? –
順便說一下,通過將產品的id保存到顯式列中的用戶模型來解釋您想要的結果。除了通過購物車從用戶到物品的正常(關係)連接之外,您是否想要「非規範化」存儲,即在用戶表中具有項目ID的「緩存」?或者你想通過使用這種方法在用戶和產品之間建立連接(即沒有從用戶到項目的其他方式,但只能通過這些列)。無論如何,因爲你的建築非常不合標準,而且從一開始看非常低效的連接方式,請解釋你爲什麼要建造它。 –
@PavelBulanov這可能是一個錯誤的方法。基本上我需要知道用戶爲了運送這些產品而選擇了哪些產品。它可以是這些相關的任何方式,但我需要知道合併的用戶標識和項目標識。只需要獲取這些數據。 –