7

我有一個模型單表繼承mogoid

class Post 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    embeds_one :comment 
end 

和我有評論類

class Comment 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    embedded_in :post 

    field :title 
    field :description 
end 

而且我從評論繼承現在

class RecentComment < Comment 
    # certain methods 
end 

我想另一個類能夠通過post創建RecentComment如果我做Post.last.build_comment(:_type => "RecentComment")新的評論將不會是_type:"RecentComment",並且同樣如果我做Post.last.build_recent_comment,它會給我錯誤,如undefined method build_recent_comment for Post class。如果postreferences_many :comments我應該做了Post.last.build_comments({}, RecentComment)沒有任何問題。但在這種情況下,我不知道如何使用RecentComment類構建對象。如果有人能幫助那會是gr8!

注:我使用gem 'mongoid', '~> 2.0.1'

+0

您可能只需要將每個註釋類型顯式放入Post類embed_one:old_comment; embeds_one:new_comment ... – monocle

+0

我想這是創建Comment的子類時遇到的問題之一。有沒有子類的好處?除名稱外,您可以有許多類都是相同的。如果可能的話,您可能希望在變得更難之前重構它。否則,我不確定如何創建所需的關聯,而不必明確地使每個關聯爲嵌入式文檔。 – monocle

+1

但所有派生類都具有與註釋相同的字段和屬性,因此將它們全部設置爲不同的嵌入式文檔是否合適? –

回答

5

也許嘗試

class Post 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    embeds_one :recent_comment, :class_name => Comment 

,也將讓您的評論類的多態

class Comment 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    field :type 
    validates_inclusion_of :type, :in => ["recent", "other"] 
+2

實際上在評論中還有其他派生類,如recentcomment,oldcomment和newcomment。如果只有一個派生類,我相信你的答案是理想的。 –

1

一個選項是嘗試這樣的:

class RecentComment < Comment 
    store_in "comment" 

    #set the type you want 
end 

但你可能只需要使用時間戳 和範圍檢索您近期, 老評論,new_comment和這樣的,

喜歡評論類中

scope :recent, where("created_at > (Time.now - 1.day)") 

那麼你可以做:

post.comments.recent