简体   繁体   English

Active Record与Memcached的关联

[英]Active Record Association with Memcached

Hi for rails model association, i know i can do this: 嗨,Rails模型协会,我知道我可以做到这一点:

For example a model class Page. 例如,模型类Page。

class Page < ActiveRecord::Base

 has_many :parts

end

I can do this: 我可以做这个:

Page.first.parts.find_by_name('body')

Page.first.parts.class actually returns Array. Page.first.parts.class实际上返回Array。 How can it activate methods for Part model? 如何激活零件模型的方法? I found the similar post on How do rails association methods work? 我发现了有关Rails关联方法如何工作的类似文章

My question is that when i try to use memcache to cache the response for parts methods. 我的问题是,当我尝试使用内存缓存来缓存部件方法的响应时。 Then when i call Page.first.parts.find_by_name('body'), it tells me that the Array doesn't have method find_by_name. 然后,当我调用Page.first.parts.find_by_name('body')时,它告诉我该数组没有方法find_by_name。 How do i solve this problem? 我该如何解决这个问题? I need to have the cache as this is one heavily used methods. 我需要缓存,因为这是一种常用的方法。

class Page
  def parts_with_cache
    Rails.cache.fetch("parts_for_page_#{id}", {:expires_in => 1.minutes}) do 
      parts_without_cache
    end
  end
  alias_method_chain :parts, :cache
end

由于您要获取与Page对象相关联的Parts对象数组,而该数组未按零件名称过滤,因此只需对结果集执行Array select方法。

body_parts = Page.first.parts.select{ |part| part.name == 'body' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM