【问题标题】:Broken links when doing fragment caching in Rails在 Rails 中进行片段缓存时链接断开
【发布时间】:2011-01-17 08:29:46
【问题描述】:

假设有一个博客,其中包含可以发表评论的帖子、cmets 和用户。用户拥有对 SEO 友好的 URL,例如 http://localhost:3000/users/john(这可以通过使用 permalink_fu 轻松完成)。

模型使用触摸来简化缓存:

class Post
  has_many :comments
end

class Comment
  belongs_to :post, :touch=>true
end

视图代码是这样的:

<%= cache @post do %>

  <h1><%= @post.title %></h1>
  <%= @post.content %>

  <%= @post.comments.each do |comment| %>
    <%= link_to h(comment.user), comment.user %> said:
    <%= comment.content %>
  <% end %>

<% end %>

现在假设 John 将他的昵称更改为 Johnny -- 他的 URL 更改为 http://localhost:3000/users/johnny。由于对帖子和 cmets 进行了片段缓存,除非片段过期,否则 John 的 cmets 将指向 John 的错误 URL。在此示例中,可以手动触摸或过期所有包含 John 的 cmets 的帖子,但在复杂的应用程序中,这将需要非常复杂的查询,并且看起来很容易出错。

这里的最佳做法是什么?我应该使用非 SEO 友好的 URL,例如 /users/13 而不是 /users/john 吗?或者也许保留一个旧 URL 列表直到缓存过期?没有任何解决方案对我来说很好。

编辑:请注意,这只是一个简化的示例——在这种情况下查询帖子并触摸它们绝对非常简单。但是一个复杂的应用程序意味着对象之间的许多关系,这使得很难跟踪每个引用用户的对象。我对此进行了一些研究——Facebook只允许设置你的用户名一次,所以这个问题不存在。

【问题讨论】:

    标签: ruby-on-rails caching permalinks fragment-caching


    【解决方案1】:

    我认为缓存帖子过期并不复杂。设置扫地机:

    class UserSweeper < ActionController::Caching::Sweeper
    observe User
    
    def after_save(user)
      user.comments.collect(&:post).each do |post|
        expire_fragment post
      end
    end
    

    【讨论】:

    • 适合这个例子,但在更大的应用程序中会很难。我更新了问题以澄清我不是在寻找简化示例的解决方案。
    • 我真的看不出有什么问题,只要定义了模型之间的关系,就可以将它们添加到清扫器中。顺便说一句,你可能想用谷歌搜索friendly_id。在您的用户场景中,它将跟踪并重定向到新的 url,直到您的缓存过期。
    • 所以friendly_id 保留了蛞蝓的历史。我不知道,但这是我正在寻找的解决方案,非常感谢,马克!
    【解决方案2】:

    例如,我会使用 before_save 过滤器

    class User
      has_many :posts
    
      before_save :touch_posts
    
      private
      def touch_posts
        Post.update_all({:updated_at => Time.now}, {:user_id => self.id}) if self.login_changed?
        true
      end
    end
    

    一个查询来更新每个用户的帖子。并不复杂。

    【讨论】:

      猜你喜欢
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      相关资源
      最近更新 更多