[英]store current_user (devise) in related table?
我將devise用於我們的用戶管理。
楷模:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :name
has_many :carts
end
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
accepts_nested_attributes_for :line_items
belongs_to :user
end
cart_controller:
def create
@cart = current_user.cart.new(cart_params)
respond_to do |format|
if @cart.save
format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
format.json { render action: 'show', status: :created, location: @cart }
else
format.html { render action: 'new' }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
private
def cart_params
params[:cart]
end
模塊:
module CurrentCart
extend ActiveSupport::Concern
private
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end
創建購物車時(添加列表項時),我想存儲在購物車表(user_id)的user.id中。 所以我想使用current_user這樣的方法
@cart = current_user.cart.new(cart_params)
使用項目創建購物車,但購物車表中的user_id保持為空。 我究竟做錯了什么?
謝謝..remco
嘗試
@cart = current_user.carts.build(cart_params)
正如馬特·吉布森(Matt Gibson)所指出的(這就是我從關聯創建新購物車的方式):
@cart = current_user.carts.build(cart_params)
但是,由於Rails 4的強大參數,我認為它無法按預期工作。 為此,您可能需要更改此設置:
private
def cart_params
params[:cart]
end
至:
private
def cart_params
params.require(:cart).permit(:name, :state) # at :name, :state use attributes which you're getting from the form for cart!
end
更改
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
至:
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = current_user.carts.create
session[:cart_id] = @cart.id # since you're setting this ID in session which you use for update later!
end
它應該是
@cart = current_user.carts.new(cart_params)
由於它具有has_many
關系,因此您必須使用購物carts
而不是購物車
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.