【问题标题】:Key based cache expiration with Mongoid embedded documents带有 Mongoid 嵌入式文档的基于键的缓存过期
【发布时间】:2012-08-27 18:30:04
【问题描述】:

您将如何设置俄罗斯娃娃之类的基于密钥的缓存到期和嵌入式文档? 正如37 signals所描述的那样

我相信在 Mongoid 3.0 中为 belongs_to 添加了 touch,但是对于嵌入式文档,您将如何处理它?

示例类:

class House
  embeds_many :persons
end

class Person
  embedded_in :house
end

查看:

<% cache ['v1', house] do %>
  <%= house.some_attribute %>
  <% house.persons.each |person| %>
    <% cache ['v1' person] do %> 
      <%= render 'houses/person', person: person %>
    <% end %>
  <% end %>
<% end %>    

概括触摸的最简单方法是什么?这样当我更新一个人时,它所嵌入的房子就会被触动。

编辑:或者这里的想法是重新渲染所有嵌入项目相对便宜?我当然可以这样做:

class Person
  after_save :touch_house
  def touch_house
    house.touch
  end
end

【问题讨论】:

    标签: ruby-on-rails-3 caching mongoid


    【解决方案1】:

    我使用观察者实现嵌入式触摸的菊花链。

    class PersonObserver < Mongoid::Observer
      def sweep(person)
        person.house.touch
      end
    
      alias_method :after_update, :sweep
      alias_method :after_create, :sweep
    end
    

    当您更新或创建一个人时,它会触及该人的房屋,从而有效地更新房屋的 update_at 时间戳。

    要使用观察者,请将其添加到您的 application.rb:

    config.mongoid.observers = :person_observer
    

    【讨论】:

    • 谢谢!唯一的问题是,当嵌入文档的深度超过 3 个时,这会变得有点混乱。
    【解决方案2】:

    我定义了这个问题:

    module ParentTouchable
    
      extend ActiveSupport::Concern
    
      def touch_parent
        self._parent.touch
      end
    
    end
    

    然后我将它包含在嵌入式模型中,因此我可以在 after_save 回调中调用 touch_parent。假设我的嵌入式模型是评论:

    class Comment
    
      include Mongoid::Document
      include ParentTouchable
    
      after_save :touch_parent
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多