2012-02-25 68 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