I'm having a hard time cacheing an object.
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
When a tracked_point
is created, my check_infractions
callback happens (technically after_save
, but that's because I want it to run on update
as well).
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)
This results in an error:
You are trying to cache a Ruby object which cannot be serialized to memcached.
This happened at the line where self.write_to_cache
was called. So I manually tried to run that code:
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
Same error. Let's try just creating a TrackedPoint
.
1.9.3-p392 :008 > tp2= TrackedPoint.create(worker_id: 88, x: 5, y: 5, recorded_at: Time.now, location_id: 15)
Same error.
If I pull the last TrackedPoint
from the database, however, I can cache it:
1.9.3-p392 :012 > tp = TrackedPoint.last
1.9.3-p392 :013 > tp.write_to_cache
true
Any ideas why cacheing in my after_save
callback and object creation is failing but if I pull the object from the database I can cache it?
- ruby 1.9.3-p392
- rails 3.2.13
- dalli 2.6.4