NoMethodError:未定义的方法`数量'

时间:2013-12-10 11:22:00

标签: ruby-on-rails

我的网页是 的 line_items_controller.rb

  def create
    @cart = current_cart
    product = Product.find(params[:product_id])
    @line_item = @cart.add_product(product.id)

    respond_to do |format|
      if @line_item.save
        format.html { redirect_to(@line_item.cart,
                                  :notice => 'Line item was successfully created.') }
        format.json { render json: @line_item, status: :created, location: @line_item }
      else
        format.html { render action: "new" }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end
  end

cart.rb

class Cart < ActiveRecord::Base
  # attr_accessible :title, :body
  has_many :line_items, :dependent => :destroy

  def add_product(product_id)
    current_item = line_items.find_by_product_id(product_id)
    if current_item
      current_item.quantity += 1
    else
      current_item = line_items.build(:product_id => product_id)
    end
    current_item
  end
end

show.html.erb

<ul>
  <% @cart.line_items.each do |item| %>
  <li> <%= item.quantity %> &times; <%= item.product.title %> </li>
      <% end %>
</ul>

add_quantity_to_line_items.rb

class AddQuantityToLineItems < ActiveRecord::Migration
  def change
    add_column :line_items, :quantity, :integer, :default => 1
  end
end

当我点击添加到购物车按钮时,我收到以下错误

 NoMethodError in LineItemsController#create
undefined method `quantity' for #<LineItem:0x007fad70aa26f0>

app/models/cart.rb:8:in `add_product'
app/controllers/line_items_controller.rb:45:in `create'

1 个答案:

答案 0 :(得分:1)

为了给你一些错误的上下文,这基本上意味着它无法从你的db加载一个特定的“列”值:

undefined method `x'

解决这个问题的方法是首先确保列在数据库中,并且您的变量将加载它(您没有使用任何选择查询等)

您收到的评论质疑您是否正确执行了迁移。原因是迁移已准备好quantity列 - 因此没有它可用通常表示没有运行迁移未在正确的环境中运行