无法使用Dalli缓存模型

时间:2013-10-03 18:14:44

标签: ruby-on-rails caching callback dalli

我很难缓存对象。

tracked_point.rb

class TrackedPoint < ActiveRecord::Base
  attr_accessible :recorded_at, :worker_id, :worker, :x, :y, :z, :geom, :location_id, :location, :frequency
  attr_accessor :x, :y
  belongs_to :worker
  belongs_to :location, counter_cache: true

  has_many :infraction_locations
  has_many :infractions, through: :infraction_locations

  validates :location_id, presence: true

  set_rgeo_factory_for_column(:geom, FACTORY)

  after_save :check_infractions

  def check_infractions
    self.write_to_cache
    self.zones.each do |zone|
      zone.write_to_cache
      ZoneWorker.perform_async(zone.id, self.id)
    end
    PrivatePub.publish_to "/tracked_points/new", :tracked_point => {x: self.geom.x, y: self.geom.y, z: self.geom.z, worker_id: self.worker_id}
    Rails.cache.write([self.cached_worker, "cached_previous_tracked_point_id"], self.id)
  end

  def write_to_cache
    Rails.cache.write([self.class.name, id], self)
  end
end

创建tracked_point后,我的check_infractions回调就会发生(技术上after_save,但那是因为我希望它也能在update上运行。

console:

1.9.3-p392 :001 > worker = Worker.find 88
1.9.3-p392 :002 > worker.tracked_points.create(x:3, y:5, location_id: 15, recorded_at: Time.now)

这会导致错误:

You are trying to cache a Ruby object which cannot be serialized to memcached.

这发生在调用self.write_to_cache的行。所以我手动尝试运行该代码:

1.9.3-p392 :007 > tp = worker.tracked_points.create(x:3, y: 3, location_id: 15, recorded_at: Time.now)
1.9.3-p392 :007 > tp.write_to_cache

同样的错误。我们试着创建一个TrackedPoint

1.9.3-p392 :008 > tp2= TrackedPoint.create(worker_id: 88, x: 5, y: 5, recorded_at: Time.now, location_id: 15)

同样的错误。

但是,如果我从数据库中提取最后一个TrackedPoint,我可以将其缓存:

1.9.3-p392 :012 > tp = TrackedPoint.last
1.9.3-p392 :013 > tp.write_to_cache
  true

为什么缓存在我的after_save回调和对象创建中的任何想法都失败但是如果我从数据库中提取对象我可以缓存它吗?

  • ruby​​ 1.9.3-p392
  • rails 3.2.13
  • dalli 2.6.4

0 个答案:

没有答案
相关问题