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 %> × <%= 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'
您是否運行遷移? –
...如果你還沒有運行'rake db:migrate' – benjaminjosephw
是的,我運行遷移,然後我得到這個錯誤 – asdfkjasdfjk