密钥的rails memcached dalli编组错误 [英] rails memcached dalli Marshalling error for key
问题描述
我的控制器中有这样的动作:
I have such action in my controller:
def my
@user = Ads::User.find current_user.id
@postings = Rails.cache.fetch("@user.postings.includes(:category)") do
@postings = @user.postings.includes(:category)
end
end
我正在尝试缓存@postings并得到这样的错误:
I'm trying to cache @postings and get such error:
Marshalling error for key '@user.postings.includes(:category)': can't dump anonymous class #<Module:0x000000048f9040>
You are trying to cache a Ruby object which cannot be serialized to memcached.
如果我尝试不包含@的情况下缓存@postings,则没有错误. 无法找出问题所在.
If I try to cache @postings without includes there are no errors. Can't figure out what is the problem.
您可以在底部找到相关模型:
You can find relevant models in the bottom:
module Ads
class User < ::User
has_many :postings, dependent: :destroy
end
end
module Ads
class Posting < ActiveRecord::Base
belongs_to :user, counter_cache: true
belongs_to :category
end
end
module Ads
class Category < ActiveRecord::Base
has_many :postings, dependent: :destroy
end
end
推荐答案
缓存提取代码全部错误. 提取的参数是一个字符串,用于标识所需的数据.您的代码正在尝试为每个用户使用相同的字符串,因此他们都将看到与第一次调用此方法将保存的帖子相同的内容.
The cache fetch code is all wrong. The parameter to fetch is a string that identifies the data you want. Your code is trying to use the same string for every user, so they would all see the same postings that would be saved by the first call of this method.
在下面的示例中,我使用用户ID和字符串"postings"来指示特定用户的所有发布.
In my example below I used the user id and a string 'postings' to indicate all postings for a specific user.
在获取块中分配 @postings 是不正确的,该块的结果(查询结果)已保存到 @postings
It is incorrect to assign @postings inside the fetch block, the result of the block (the query result) is saved to @postings
最后,ActiveRecord会延迟进行实际的数据库调用,直到绝对必要为止.查询末尾的 .all 调用将返回数据,该数据是您要缓存的内容,而不是用于创建查询的配置数据.
Finally, ActiveRecord delays making the actual database call until absolutely necessary. The .all call at the end of the query will return the data, and the data is what you want cached, not the configuration data used to create a query.
这是正确的代码:
@postings = Rails.cache.fetch("#{@user.id}:postings") do
@user.postings.includes(:category).all
end
这篇关于密钥的rails memcached dalli编组错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!