2015-01-14 4 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

흐름 제어에서 wup signup.update. '가입? signup.update! : puts c_array [0]'배열에 데이터베이스 값이 없습니다 – Anthony

답변

2

배열에서 항상 Signupcustomer_id이있는 것은 아니며 때로는 Signup 대신 nil을 반환합니다. 다음 체크를 추가하기 만하면됩니다.

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!''를 제거하십시오. 긴 날이었고 나는 휴식 할 필요가있었습니다. :) –

관련 문제