【发布时间】:2013-12-11 17:15:44
【问题描述】:
我正在使用以下模型制作购物车:
用户:
class User < ActiveRecord::Base
has_secure_password
has_one :cart
end
购物车:
class Cart < ActiveRecord::Base
belongs_to :user
has_many :items
validates :item, uniqueness: true
end
项目:
class Item < ActiveRecord::Base
belongs_to :product
belongs_to :cart
end
控制器:
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
@user.create_cart
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: @user }
else
format.html { render action: 'new' }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
所以它应该在创建帐户时为每个user 创建一个新的cart。但是,当我创建一个新用户时,我确实会收到此错误:
undefined method `item' for #<Cart id: nil, user_id: 1, created_at: nil, updated_at: nil>
Extracted source (around line #31):
29 respond_to do |format|
30 if @user.save
31 @user.create_cart
32 format.html { redirect_to @user, notice: 'User was successfully created.' }
33 format.json { render action: 'show', status: :created, location: @user }
34 else
为什么会这样?我该怎么做才能让它发挥作用?
【问题讨论】:
标签: ruby-on-rails forms registration shopping-cart