2012-02-25 76 views
0

我有几个可评论的模型(文章,文章等)。目前各commentable模型包含以下关联Rails多态模型 - 基类

has_many :comments, :as => :commentable

和注释模型包含:

belongs_to :commentable, :polymorphic => true

我commentable模型有一些相似的特点,我想他们是能够使用一些相同的功能。但是,我认为MTI(多表继承)对于这种情况可能是过度的。我可以创建一个他们都继承的基础模型类吗?即:

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 

回答

1

你可能最好创建一个可评论的模块,然后包含该模块。

module Commentable 
    def some_function 
     ... 
    end 
end 

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

    include Commentable 
    .... 
end 

如果你想避免重复has_manyvalidates_presence_of语句你可以按照你的模块acts_as模式。

在这种情况下,你可以不喜欢

# 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 
+0

伟大的信息,感谢您的! – 2012-02-26 00:11:36