Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_comments({}, 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'

like image 539
Sadiksha Gautam Avatar asked May 11 '11 12:05

Sadiksha Gautam


Video Answer


2 Answers

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"]
like image 84
monocle Avatar answered Oct 09 '22 12:10

monocle


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
like image 21
Andres Avatar answered Oct 09 '22 12:10

Andres