7

我有一个模型

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

现在我希望能够创建RecentComment通过,post如果我这样做Post.last.build_comment(:_type => "RecentComment")新的评论将不会是_type:"RecentComment",同样如果我这样做Post.last.build_recent_comment,它会给我错误的说 sth like undefined method build_recent_comment for Post class。如果post有的话,references_many :comments我应该Post.last.build_comments({}, RecentComment)没有任何问题。但我不知道RecentComment在这种情况下如何用类构建一个对象。如果有人可以帮助那将是 gr8!

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

4

2 回答 2

5

也许试试

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

  embeds_one :recent_comment, :class_name => Comment

并使您的 Comment 类具有多态性

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

  field :type
  validates_inclusion_of :type, :in => ["recent", "other"]
于 2011-05-21T05:23:35.630 回答
1

一种选择是尝试类似的方法:

class RecentComment < Comment
  store_in "comment"

  #set the type you want
end

但您可能只使用时间戳和范围来检索您最近的旧评论、新评论等,

喜欢在评论类中

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

那么你可以这样做:

post.comments.recent
于 2011-08-05T15:56:07.093 回答