2016-09-19 58 views
0

Order has_many RentalItemsRails - 未更改的屬性已註冊爲已更改?

所以我對Order此回調,其中一點是,xyz_method運行,只要任何孩子RentalItemsizespecification改變,或一個新的子RentalItem已被添加。

before_save do 
    if rental_items_attributes_modified? 
    xyz_method 
    end 
end 

def rental_items_attributes_modified? 
    self.rental_items.each do |ri| 
    # as long as ONE item had ONE thing changed, we return true or it's a new record 
    puts "in RI modified?" 
    puts "#{ri.new_record?} with ID #{ri.id}" 
    puts "#{ri.specification_changed?} from #{ri.specification_was} to #{ri.specification}" 
    puts "#{ri.size_changed?} from #{ri.size_was} to #{ri.size}" 
    if ri.specification_changed? || ri.size_changed? || ri.new_record? 
     return true 
    end 
    end 
    return false 
end 

所有puts都幫我調試...我不知道爲什麼,但rental_items_attributes_modified?保持返回true,因爲對於RentalItems之一,specification_changed?回報true即使它不是...這是有關日誌輸出:

# testing the first child RI 
in RI modified? 
false with ID 1 
false from blue to blue 
false from Regular to Regular 

# testing the second child RI 
in RI modified? 
false with ID 2 
true from to # <<< why is this happening??? 
false from Regular to Regular 

對於怪異的第二個孩子RI問題,specification = ""最初,什麼被傳遞是PARAMS這樣的:

"rental_items_attributes"=>[{"id"=>"2", "specification"=>"", "size"=>"Regular"}] 

我已經試過這個獨立的控制檯,它觸發正確的行爲...

# for an order whose child RI initially had a blank specification & size 
o.update_attributes({"rental_items_attributes" => [{"id" => 79, "specification" => ""}]}) 
=> 
in RI modified? 
false with ID 79 
false from to 
false from to 
+1

「規格」是否有默認值?這可能是零與「」的問題。 –

+0

我看着它,有同樣的懷疑,這不是問題;當孩子第一次創建時''''規格'開頭爲'''' – james

回答

0

這只是一個評論,但我不能因爲少聲譽寫評論。 (因此,您可以忽略此評論。)

您有沒有檢查before_save塊中的值? Like,

ri.specification_was.nil? 
ri.specification.nil? 

兩者都是假的?

+0

OMG我很愚蠢......所以我對John Feltz的回答是'nil'不是問題,我完全確定這一點。你的回答讓我想重複檢查,所以我做了,結果發現其中一個實例讀爲'nil',所以當我有點瘋狂並且挖掘出爲什麼事實證明有一個GODDAMN TYPO,並且我已經通過像'speciification =>「」''這樣的參數永遠不會擊中數據庫!啊 – james