簡體   English   中英

Mongoid版本控制范圍

[英]Mongoid Versioning Scopes

當您混入Mongoid :: Versioning模塊時,Mongoid具有內置的版本控制。 它對我來說確實很好用,但是我不太擅長在模型上使用版本。 讓我給你舉個例子。 假設我正在構建一個博客應用程序(不是)。

我的模型是郵政。 假設我想查找單個帖子的所有先前發布的版本。 以下作品:

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類,但它不是很喜歡。 我有一個解決方法,我只是想了解更多有關內置的​​Versioning Mongoid提供的信息,尤其是如何擴展Version類。

您定義的范圍非常非常錯誤,原因有兩個:

  1. 您不能將字符串傳遞給:where參數。 您需要傳遞哈希
  2. 作用域是在類(在這種情況下為Post )上定義的,因此您不能引用self.versions因為self引用Post類而不是任何特定的post

解決的辦法是用matches在Mongoid助手(它是一個快捷方式到蒙戈的$ elemMatch ):

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

除非您真的知道自己在做什么,否則我不建議您對Version類進行monkeypatching。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM