我有一個模型單表繼承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
。如果post
有references_many :comments
我應該做了Post.last.build_comments({}, RecentComment)
沒有任何問題。但在這種情況下,我不知道如何使用RecentComment
類構建對象。如果有人能幫助那會是gr8!
注:我使用gem 'mongoid', '~> 2.0.1'
您可能只需要將每個註釋類型顯式放入Post類embed_one:old_comment; embeds_one:new_comment ... – monocle
我想這是創建Comment的子類時遇到的問題之一。有沒有子類的好處?除名稱外,您可以有許多類都是相同的。如果可能的話,您可能希望在變得更難之前重構它。否則,我不確定如何創建所需的關聯,而不必明確地使每個關聯爲嵌入式文檔。 – monocle
但所有派生類都具有與註釋相同的字段和屬性,因此將它們全部設置爲不同的嵌入式文檔是否合適? –