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

Commentableモジュールを作成し、そのモジュールを組み込む方がよいでしょう。

module Commentable 
    def some_function 
     ... 
    end 
end 

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

    include Commentable 
    .... 
end 

あなたがあなたのモジュールのacts_asパターンをたどることができhas_manyvalidates_presence_of文の重複を回避したい場合。あなたは

# 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

偉大な情報のような何かを行うことができ、その場合には

、そのためにありがとう! –

関連する問題