当我尝试将内存中的对象保存到数据库中,然后用 Dalli 缓存该对象时,我的行为很奇怪。
class Infraction << ActiveRecord::Base
has_many :infraction_locations
has_many :tracked_points, through: :infraction_locations
end
class TrackedPoint << ActiveRecord::Base
has_many :infraction_locations
has_many :infractions, through: :infraction_locations
end
class InfractionLocation << ActiveRecord::Base
belongs_to :infraction
belongs_to :tracked_point
belongs_to :rule
end
这有效:
i = Infraction.create
i.tracked_points << TrackedPoint.create(location_id: 1)
i.save
Rails.cache.write "my_key", i
这也有效:
i = Infraction.new
i.tracked_points << TrackedPoint.create(location_id: 1)
i.save
Rails.cache.write "my_key", i
请注意,对象(在第二种情况下只是TrackedPoint
)通过调用 create 隐式保存到数据库中。
我还发现重新加载i
允许我将对象写入缓存。所以这有效:
i = Infraction.new
i.tracked_points << TrackedPoint.new(location_id: 1)
i.save
i.reload
Rails.cache.write "my_key", i
这失败了:
i = Infraction.new
i.tracked_points << TrackedPoint.new(location_id: 1)
i.save
Rails.cache.write "my_key", i
但是,如果我做了一些奇怪的欺骗,我可以让失败的例子工作:
i = Infraction.new
i.tracked_points << TrackedPoint.new(location_id: 1)
i.save
copy = i.dup
copy.tracked_points = i.tracked_points.to_a
Rails.cache.write "my_key", copy
在我失败的示例中,我可以在将违规 ( i
) 保存到数据库之前对其进行缓存,如下所示:
i = Infraction.new
i.tracked_points << TrackedPoint.new(location_id: 1)
Rails.cache.write "what", i
根据 Dave 的想法,我尝试build
代替<<
forTrackedPoint
以及添加 a accepts_nested_attributes_for :tracked_points
to Infraction
,但这些都不起作用。
我在日志中收到编组/序列化程序错误:
You are trying to cache a Ruby object which cannot be serialized to memcached.
我正在运行 Rails 3.2.13 和 Dalli 2.7.0
编辑
另请参阅:通过以下方式缓存 has_many 的 ActiveRecord 对象: