为什么在Rails中while循环+ sleep + ActiveRecord.find不应该返回记录呢?

Cha*_*son 0 ruby-on-rails comet

我正在尝试在我的Rails应用程序中实现一个彗星方法.我有以下内容:

def poll
  records = []
  start_time = Time.now.to_i

  while records.length == 0 do
    records = Something.find(:all,
        :conditions => { :some_condition => false})

    if records.length > 0
      break
    end

    sleep 1

    if Time.now.to_i - start_time >= 10
      break
    end
  end

  responseData = []

  records.each do |record|
    responseData << {
      'something' => record.some_value
    }

    # Flag message as received.
    record.some_condition = true
    record.save
  end

  render :text => responseData.to_json
end
Run Code Online (Sandbox Code Playgroud)

现在,当我手动转到URL时,它会在那里等待10秒并按预期超时.如果我修改我的数据库以便Something.find()返回记录然后再次转到URL,则调用立即返回.

但是,如果我转到URL,然后我快速对数据库运行更新,以便Something.find()应该找到记录,它只是坐在那里直到它在10秒后超时.我希望在我做出更改并返回后,它应该立即看到对数据库的更改.

有什么想法吗?我也愿意接受有关改进的建议.

Har*_*tty 5

这是因为您的查询默认是缓存的.试试这个:

records = Something.uncached{Something.find(:all,
            :conditions => { :some_condition => false})}
Run Code Online (Sandbox Code Playgroud)

参考文献:第1条