【问题标题】:rails memcached dalli Marshalling error for keyrails memcached dalli 密钥的编组错误
【发布时间】:2012-12-11 09:18:55
【问题描述】:

我的控制器中有这样的动作:

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 并得到这样的错误:

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 而不包含任何错误。 不知道是什么问题。

您可以在底部找到相关型号:

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

【问题讨论】:

  • 请贴出相关模型:User、Posting、Category。
  • 我已添加有问题的相关模型

标签: ruby-on-rails memcached rails-engines dalli


【解决方案1】:

缓存获取代码全部错误。 fetch 的参数是一个字符串,用于标识您想要的数据。您的代码尝试为每个用户使用相同的字符串,因此他们都会看到相同的帖子,这些帖子将在第一次调用此方法时保存。

在下面的示例中,我使用了用户 ID 和字符串“postings”来指示特定用户的所有帖子。

在fetch块内部分配@postings不正确,块的结果(查询结果)保存到@postings

最后,ActiveRecord 会延迟进行实际的数据库调用,直到绝对必要为止。查询结束时的 .all 调用将返回数据,并且数据是您要缓存的数据,而不是用于创建查询的配置数据。

这是正确的代码:

@postings = Rails.cache.fetch("#{@user.id}:postings") do
    @user.postings.includes(:category).all
end

【讨论】:

    【解决方案2】:

    它可能会抱怨这个:

    class User &lt; ::User

    你有什么理由不使用:

    class User &lt; ActiveRecord::Base

    【讨论】:

    • 不,引擎中的类用户。所以我只是从主机应用程序继承用户。以前的回复对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2014-12-12
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多