Does anyone know how to do a polymorphic association in Mongoid
that is of the relational favor but not the embedding one.
For instance this is my Ass
Here's how you would implement Polymorphic Associations in Mongoid for a Comment
model that can belong to both a Post
and Event
model.
The Comment
Model:
class Comment
include Mongoid::Document
belongs_to :commentable, polymorphic: true
# ...
end
Post
/ Event
Models:
class Post
include Mongoid::Document
has_many :comments, as: :commentable
# ...
end
Using Concerns:
In Rails 4+, you can use the Concern pattern and create a new module called commentable
in app/models/concerns
:
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
end
end
and just include
this module in your models:
class Post
include Mongoid::Document
include Commentable
# ...
end