【问题标题】:Mongoid Versioning ScopesMongoid 版本控制范围
【发布时间】:2010-12-30 19:44:29
【问题描述】:

当您混入 Mongoid::Versioning 模块时,Mongoid 具有内置的版本控制。它对我来说非常有效,但我在模型上使用版本时表现不佳。让我给你举个例子。假设我正在构建一个博客应用程序(我不是)。

我的模型是 Post。假设我想查找单个帖子的所有以前发布的版本。以下作品:

post = Post.first  # just grab something
published_posts = post.versions.find_all{ |v| v.published == true }

等等。然后我可以用 published_posts 或其他东西做点什么。我很想为此创建一个命名范围,所以我没有将 find_all 块放在我的视图中,但我不知道如何覆盖 Version 类的内置功能。

我在 Post 类中尝试了各种范围。例如:

# I can't get this and other variations on this to work
scope :versions_published, 
  :where => 'self.versions.find_all{ |v| v.published == true }'

我也试过猴子修补 Version 类,但它不太喜欢它。我有一个解决方法,我只是希望了解更多关于 Mongoid 提供的内置版本控制,特别是如何扩展 Version 类。

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    您定义的范围非常非常错误,有两个根本原因:

    1. 您不能将字符串传递给:where 参数。你需要传入一个哈希
    2. 范围是在类上定义的(在这种情况下为Post),因此您不能引用self.versions,因为self 指的是Post 类而不是任何特定的帖子

    解决方案是在 Mongoid 中使用matches 助手(这是Mongo's $elemMatch 的快捷方式):

    class Post
      #...
      scope :versions_published, where(:versions.matches => {:published => true})
      #...
    end
    

    除非您真的知道自己在做什么,否则我不建议对 Version 类进行猴子补丁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      相关资源
      最近更新 更多