0

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 有问题的任何其他人,因为这当然值得在您的调试中检查。

4

1 回答 1

0

active_questions_for_standard_and_element可能确实返回一个数组,但通过应用[index-1]它,您将从该数组中获取一个元素。除非您的数组旨在包含子数组,否则您不应期望active_questions_for_standard_and_element(...)[index-1]生成数组。

于 2013-08-28T01:17:18.470 回答