Mongoid relational Polymorphic Association

后端 未结 3 1809
南旧
南旧 2021-02-10 06:14

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

3条回答
  •  一整个雨季
    2021-02-10 06:49

    Rails 4+

    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
    

提交回复
热议问题