2015-01-14 55 views
0

此代碼顯示註冊,它顯示數據。無法更新紅寶石環路內的數據庫

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

在流量控制中換行signup.update。 '註冊? signup.update! :puts c_array [0]'你的數組有一個值,你的數據庫不會 – Anthony

回答

2

看起來像你並不總是有Signupcustomer_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 
+0

謝謝@Rustam。您的解決方案非常有意義。我只需稍微修改它就可以在一行上進行更新。 '''signup.update(:created_at => c_array [1])'''並刪除'''signup.update!'''。這是漫長的一天,我需要休息。 :) –