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? i.e.:
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.
If you want to avoid duplicating the
has_manyand thevalidates_presence_ofstatements you could follow theacts_aspattern for your module.In that case you could do something like