在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
?而且,我该如何阻止它?
UPDATE
看来这个问题有一些与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问题的人,因为这在你的调试中值得检查。
这里有什么困惑?类型正在改变,因为你正在索引数组.. ..'[index-1]'< - –
对不起,我遗漏了一个重要的细节;已经更新了问题 –
我现在已经删除了对[[index-1]'的引用,因为我真正的问题是没有它,我得到了相同的结果。 –