1

你将如何设置一个俄罗斯娃娃,如基于密钥的缓存过期与嵌入式文档?如37 个信号所述

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

示例类:

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
4

2 回答 2

0

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

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
于 2012-10-17T17:11:49.423 回答
0

我定义了这个问题:

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
于 2016-03-10T14:37:36.833 回答