我使用设计用于我们的用户管理。
模特:
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仍为空。我究竟做错了什么?
thanks..remco
答案 0 :(得分:1)
尝试
@cart = current_user.carts.build(cart_params)
答案 1 :(得分:1)
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
答案 2 :(得分:0)
应该是
@cart = current_user.carts.new(cart_params)
由于has_many
关系,您必须使用carts
而不是购物车