开发者

single table inheritance with embeds_one mogoid

I have a model

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

  embeds_one :comment
end

and I have comment class

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

  embedded_in :post

  field :title
  field :description
end

And I have another class inherited from comment

class RecentComment < Comment
  # certain methods
end

Now I want to be able to create RecentComment through post if I do Post.last.build_comment(:_type => "RecentComment") the new comment will not be of _type:"RecentComment", and similarly if I do Post.last.build_recent_comment, it gives me error saying sth like undefined method build_recent_comment for Post class. If the post had references_many :comments I should have done Post.last.build_开发者_StackOverflowcomments({}, RecentComment) without any problems. But I don't know about how to build an object with RecentComment class in this case. If anybody could help that'd be gr8!

Note: I am using gem 'mongoid', '~> 2.0.1'


Maybe try

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

  embeds_one :recent_comment, :class_name => Comment

and just make your Comment class polymorphic

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

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


one option is to try something like:

class RecentComment < Comment
  store_in "comment"

  #set the type you want
end

but you might just use timestamps and scope to retrieve your recent, old comment, new_comment and such,

like within the comment class

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

then you can do:

post.comments.recent
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜