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
有帮助吗?

解决方案

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

其他提示

It's likely complaining about this:

class User < ::User

Is there any reason why you're not using:

class User < ActiveRecord::Base

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top