2011-01-31 66 views
2

檢查下面的註釋。爲什麼在我做p variant_attributes之前,blank?方法返回錯誤,而在它之後,它工作正常嗎?未定義方法'零'... ActiveSupport :: OrderedHash

Ruby on Rails的1.9.2-P0 3.0.3

p variant_attributes.blank? 
# => NoMethodError Exception: undefined method `zero?' for {"Brocade w/ Grande Stripe backing"=>3}:ActiveSupport::OrderedHash 
p variant_attributes 
# => [#<VariantAttribute id: 1251, variant_id: 561, product_option_id: 838, value: "Brocade w/ Grande Stripe backing">] 
p variant_attributes.blank? 
# => false 

回答

7

如果variant_attributes是一種記錄ActiveRecord的集合(它看起來像),那麼這可能是因爲Rails使用延遲加載獲取記錄從數據庫中,但blank?方法不會觸發實際加載。

您可能需要調用all方法上variant_attributes手動觸發裝載,或者如果你不想這樣做,你可以去爲variant_attributes.count.zero?,而不是variant_attributes.blank?

Pratik Naik's blog post about ActiveRecord 3.0查詢界面的細節

相關問題