表单提交时带有rails的未定义方法`item'

时间:2013-12-11 17:15:44

标签: ruby-on-rails forms registration shopping-cart

我正在制作一个包含以下型号的购物车:

用户:

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

因此,在创建帐户时,应为每个cart创建一个新的user。但是,当我建立新用户时,我会收到此错误:

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

为什么会这样,我该怎么做才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

您的Cart模型包含validates :item,暗示/要求item表中有carts列。我怀疑情况并非如此。