How to specify commentable_type field with polymorphic associations?

I have two models: Article and Post, which inherit from the base ContentBase model.

You can leave comments on articles and posts, so I use the Polymorphic association between comments and an article or post.

However, since both Article and Post inherit from ContentBase, the commentable_type field ends with "ContentBase" for both, and all screws.

Is there a way to specify the commentable_type field in the has_many relationship in the article and post?

Edit:

By "screws all up" I mean, if there is an article with ID = 1 and Post with ID = 1, and I add a Comment with comment_id = 1, commentable_type = ContentBase, this comment will be displayed for both the article and the Post .

Here is the code:

class Article < BaseContent
  has_many :comments, :as => :commentable
end

class Post < BaseContent
  has_many :comments, :as => :commentable
end

:

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end
+3
2

ContentBase? ?

Module BaseContent
   def self.included(base)
      base.class_eval do
        validates_presence_of     :somefield
        validates_length_of       :someotherfield

        def my_method
          "hello"
        end
      end
   end

end
+2

, . , XXX_type , . , , , .

, Single Table Inheritance, ActiveRecord . , Article Post ContentBase, ( "content_bases" ). ID = 1 Post ID = 1.

:

+1

Source: https://habr.com/ru/post/1698871/


All Articles