无法在ruby循环内更新数据库

时间:2015-01-14 03:34:36

标签: ruby sqlite sinatra datamapper

此代码显示注册,显示数据。

 cids.each {|c_array|
    puts c_array[0]
    signup = Signup.first(:customer_id => c_array[0])
    #signup.created_at = c_array[1]
    puts "signup is " + signup.inspect
    #signup.update!
  }

结果:

signup is #<Signup @id=1 @user_id=1 @customer_id=74843293 @company_id=6 @created_at=Thu, 08 Jan 2015 22:21:43 -0500 @updated_at=Thu, 08 Jan 2015 22:21:43 -0500>

signup is #<Signup @id=2 @user_id=1 @customer_id=67170279 @company_id=6 @created_at=Thu, 08 Jan 2015 22:21:43 -0500 @updated_at=Thu, 08 Jan 2015 22:21:43 -0500>

signup is #<Signup @id=3 @user_id=1 @customer_id=69079324 @company_id=6 @created_at=Thu, 08 Jan 2015 22:21:44 -0500 @updated_at=Thu, 08 Jan 2015 22:21:44 -0500>

signup is #<Signup @id=4 @user_id=1 @customer_id=60434274 @company_id=6 @created_at=Thu, 08 Jan 2015 22:21:44 -0500 @updated_at=Thu, 08 Jan 2015 22:21:44 -0500>

等等。

但是当我取消注释另外两行时:

 cids.each {|c_array|
    puts c_array[0]
    signup = Signup.first(:customer_id => c_array[0])
    signup.created_at = c_array[1]
    puts "signup is " + signup.inspect
    signup.update!
  }

它打破了:

NoMethodError - undefined method `created_at=' for nil:NilClass:
    customerController.rb:49:in `block (2 levels) in <class:CustomerController>'

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

好像你的数组中Signup并不总是customer_id,有时会返回nil而不是Signup个对象。只需添加以下支票:

cids.each do |c_array|
  puts c_array[0]
  signup = Signup.first(:customer_id => c_array[0])
  puts "signup is " + signup.inspect
  unless signup.nil?
    signup.created_at = c_array[1]  
    signup.update!
  end
end