使用embeds_one mongoid进行单表继承

时间:2011-05-11 12:02:13

标签: ruby-on-rails mongoid single-table-inheritance ruby-1.9.2

我有一个模特

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,同样如果undefined method build_recent_comment for Post class post 1}},它给我一个错误的说法...... references_many :comments。如果Post.last.build_comments({}, RecentComment)RecentComment我应该gem 'mongoid', '~> 2.0.1'没有任何问题。但在这种情况下,我不知道如何使用{{1}}类构建对象。如果有人可以帮助那就是gr8!

注意:我使用的是{{1}}

2 个答案:

答案 0 :(得分: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"]

答案 1 :(得分: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