Rails 新手问题 -- 应用 rails 进行敏捷 web 开发上的问题

匿名 · 2013年03月19日 · 最后由 Rei 回复于 2013年03月19日 · 4103 次阅读

刚刚接触 rails,按着《应用 rails 进行敏捷 web 开发》上的 depot 的案例走下来遇到了一个问题。在创建智能的购物车这一章节中报错 NoMethodError in LineItemsController#create undefined method `+' for nil:NilClass 在 cart 的 model 中我做了稍微的修改

#在购物车中添加商品
 def add_product(product)
      #在line_item中根据product.id查找到对应的product
   current_item = line_items.find_by_product_id(product.id)
   if current_item
       current_item.quantity += 1
   else
       current_item = line_items.build
       current_item.product = product
   end
   current_item
 end

line_items_controller 中的 create 方法

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


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

因为刚刚接触 rails,不太了解,希望大神指导

应该有错误的行号,检查一下,错误是空 nil。

检查下 current_item.quantity 初始化了么

匿名 #3 2013年03月19日

#2 楼 @NonTwitter 修改 line_items 表的结构添加一个 quantity 字段,使用迁移来修改数据库。 rails g migration add_quantity_to_line_items quantity:integer 之后修改了在 db 目录下对应的文件

class AddQuantityToLineItems < ActiveRecord::Migration
  def self.up
       #默认是1
    add_column :line_items, :quantity, :integer, :default => 1      
  end
  def self.down
    remove_column :line_items, :quantity
  end
  def change
    add_column :line_items, :quantity, :integer
  end
end

执行迁移应用到数据库的命令,我想这里已经对 current_item.quantity 进行初始化了吧。。。

#3 楼 @gelihai1991 change 就是 up 和 down 的总和了,不用都写,我估计 change 把 quantity 的默认值改回 nil,然后相加的时候没有 + 操作产生异常。

匿名 #5 2013年03月19日

#4 楼 @Rei 我已经吧 change 删掉了,依然出现这个错误。情景是这样的,往购物车里面添加商品,如果购物车不存在则创建一个购物车,如果已经存在则将商品直接加入购物车中。若买同样的商品多个,利用 quantity 计数。现在情况是,如果购物车中已经存在这个商品了,再点击加入购物车就会报如上错。

#5 楼 @gelihai1991 脏数据。可以进控制台操作

rails c
> LineItem.where(:quantity => nil).update_all(:quantity => 1)
匿名 #7 2013年03月19日

#6 楼 @Rei 谢谢啊,问题解决了。但是为什么会出现这种情况呢

#5 楼 @gelihai1991 虽然已经删掉了 change,但是数据库结构已经被写进去了,开发环境下修正这个错误,可以用这个

rake db:migrate:redo STEP=1

重跑最后一次 migrate 任务。不过这样会丢失数据,生产环境不能这样做,只有新增 migrate 修正了。

#7 楼 @gelihai1991 就是 migrate 任务写重了,change = up + down。

当前数据库状况可以打开 db/schema.rb 看看。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号