ruby-on-rails – 生成为ActiveRecord :: Relation的Rails Cache
发布时间:2020-12-17 04:06:03 所属栏目:百科 来源:网络整理
导读:我试图生成一个片段缓存(使用Dalli / Memcached存储)但是密钥是用“#”生成的,因为Rails似乎没有意识到存在缓存值并且正在命中数据库. 我在视图中的缓存键如下所示: cache([@jobs,"index"]) do 控制器具有: @jobs = @current_tenant.active_jobs 使用这样
我试图生成一个片段缓存(使用Dalli / Memcached存储)但是密钥是用“#”生成的,因为Rails似乎没有意识到存在缓存值并且正在命中数据库.
我在视图中的缓存键如下所示: cache([@jobs,"index"]) do 控制器具有: @jobs = @current_tenant.active_jobs 使用这样的实际Active Record查询: def active_jobs self.jobs.where("published = ? and expiration_date >= ?",true,Date.today).order("(featured and created_at > now() - interval '" + self.pinned_time_limit.to_s + " days') desc nulls last,created_at desc") end 查看rails服务器,我看到缓存读取,但SQL查询仍然运行: Cache read: views/#<ActiveRecord::Relation:0x007fbabef9cd58>/1-index Read fragment views/#<ActiveRecord::Relation:0x007fbabef9cd58>/1-index (1.0ms) (0.6ms) SELECT COUNT(*) FROM "jobs" WHERE "jobs"."tenant_id" = 1 AND (published = 't' and expiration_date >= '2013-03-03') Job Load (1.2ms) SELECT "jobs".* FROM "jobs" WHERE "jobs"."tenant_id" = 1 AND (published = 't' and expiration_date >= '2013-03-03') ORDER BY (featured and created_at > now() - interval '7 days') desc nulls last,created_at desc 关于我可能做错什么的任何想法?我确定它必须与密钥生成和ActiveRecord :: Relation进行,但我不确定如何. 解决方法
我遇到过类似的问题,我无法成功地将关系传递给缓存函数,而@jobs变量是一种关系.
我编写了一个解决缓存密钥的解决方案来处理这个问题以及我正在处理的其他问题.它主要涉及通过迭代关系生成缓存键. 我的网站上有完整的文章. http://mark.stratmann.me/content_items/rails-caching-strategy-using-key-based-approach 总之,我在ActiveRecord :: Base中添加了一个get_cache_keys函数 module CacheKeys extend ActiveSupport::Concern # Instance Methods def get_cache_key(prefix=nil) cache_key = [] cache_key << prefix if prefix cache_key << self self.class.get_cache_key_children.each do |child| if child.macro == :has_many self.send(child.name).all.each do |child_record| cache_key << child_record.get_cache_key end end if child.macro == :belongs_to cache_key << self.send(child.name).get_cache_key end end return cache_key.flatten end # Class Methods module ClassMethods def cache_key_children(*args) @v_cache_key_children = [] # validate the children args.each do |child| #is it an association association = reflect_on_association(child) if association == nil raise "#{child} is not an association!" end @v_cache_key_children << association end end def get_cache_key_children return @v_cache_key_children ||= [] end end end # include the extension ActiveRecord::Base.send(:include,CacheKeys) 我现在可以通过这样做来创建缓存片段 cache(@model.get_cache_key(['textlabel'])) do (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |