在product.rb
中,我有:
def active_question_description_for_standard_element_and_index(standard, element, index)
active_questions_for_standard_and_element(standard, element)[index-1].try(:description)
end
def active_questions_for_standard_and_element(standard, element)
Rails.cache.fetch([self, standard, element, "product_active_questions_for_standard_and_element"]) {
questions_for_standard_and_element(standard, element).select{|q| q.active}}
end
该active_question_description_for_standard_element_and_index
方法给了我这个错误:NoMethodError: undefined method 'description' for 0:Fixnum
。
所以,我self.touch
先绕过缓存,然后进入active_questions_for_standard_and_element(standard, element)
. 这返回0
。
“嗯,”我想,“这意味着返回一个数组,即使它是一个空数组。它并不意味着返回一个 Fixnum。”
所以,我尝试questions_for_standard_and_element(standard, element).select{|q| q.active}
,然后返回[]
,就像你期望的那样。
那么,为什么 Rails 会转换[]
为0
? 而且,我该如何阻止它?
更新
似乎这个问题与 Rails.cache 有关,因为当我从方法中删除它时,一切正常。到目前为止,我不知道问题是什么,因为写入[]
缓存工作得很好;0
再次读回时它不会转换为。
[1] pry(main)> Rails.cache.write('foo', [])
Cache write: foo
Dalli::Server#connect 127.0.0.1:11211
=> true
[2] pry(main)> Rails.cache.read('foo')
Cache read: foo
=> []
更新 2:找到答案
另一种方法是写入相同的缓存键。将此作为提示留给对 Rails.cache 有问题的任何其他人,因为这当然值得在您的调试中检查。