2013-12-10 72 views
0

我的页面 line_items_controller.rbNoMethodError:未定义的方法`量”

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' 
+2

您是否运行迁移? –

+0

...如果你还没有运行'rake db:migrate' – benjaminjosephw

+0

是的,我运行迁移,然后我得到这个错误 – asdfkjasdfjk

回答

1

为了给你一定的误差范围内,这基本上意味着它不能从你的db中加载一个特定的“列”值:

undefined method `x' 

解决方法是确保firstl y该列在数据库中,并且您的变量将加载它(您没有使用任何select查询等)

您收到的评论质疑您是否正确执行了您的迁移。原因是迁移有quantity列准备就绪 - 所以没有它通常指示没有运行迁移未在正确的环境中运行

相关问题