简体   繁体   中英

Rails polymorphic models - base class

I have several models that are commentable (article, post, etc.). At the moment each commentable model contains the following association

has_many :comments, :as => :commentable

and the comment model contains:

belongs_to :commentable, :polymorphic => true

My commentable models share some similar characteristics, and I'd like them to be able to use a few of the same functions. However, I think MTI (multiple-table inheritance) might be overkill for the situation. Is it possible/acceptable for me to just create a base model class that they both inherit? ie:

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

class Commentable < ActiveRecord::Base
  has_many :comments, :as => :commentable
  validates_presence_of :body
  def some_function
    ...
  end
end

class Article < Commentable
  ...
end

class Post < Commentable
  ...
end

You're probably better off to create a Commentable module and then include that module.

module Commentable
    def some_function
       ...
    end
end

class Article < ActiveRecord::Base
    has_many :comments, :as => :commentable
    validates_presence_of :body

    include Commentable
    ....
end

If you want to avoid duplicating the has_many and the validates_presence_of statements you could follow the acts_as pattern for your module.

In that case you could do something like

# lib/acts_as_commentable.rb
module ActsAsCommentable

  extend ActiveSupport::Concern

  included do
  end

  module ClassMethods
    def acts_as_commentable
      has_many :comments, :as => :commentable
      validates_presence_of :body
    end
  end

  def some_method
    ...
  end

end
ActiveRecord::Base.send :include, ActsAsCommentable

# app/models/article.rb
class Article < ActiveRecord::Base
  acts_as_commentable
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM