2013-12-10 113 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列準備就緒 - 所以沒有它通常指示沒有運行遷移未在正確的環境中運行

相關問題