1

我很难缓存一个对象。

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

创建a 时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回调和对象创建中缓存失败但是如果我从数据库中提取对象我可以缓存它?

  • 红宝石 1.9.3-p392
  • 导轨 3.2.13
  • 达利 2.6.4
4

0 回答 0