rails memcached dalli Marshalling error for key

心不动则不痛 提交于 2019-12-11 04:31:45

问题


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

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.

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

回答1:


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.

In my example below I used the user id and a string 'postings' to indicate all postings for a specific user.

It is incorrect to assign @postings inside the fetch block, the result of the block (the query result) is saved to @postings

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.

Here is the correct code:

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



回答2:


It's likely complaining about this:

class User < ::User

Is there any reason why you're not using:

class User < ActiveRecord::Base



来源:https://stackoverflow.com/questions/14030025/rails-memcached-dalli-marshalling-error-for-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!