2012-03-11 12 views
2

私は3つのモデルと多相関係を持っています。 ポスト:モデル内のコードを簡略化

#models/post.rb 

class Post < ActiveRecord::Base 

    after_create :create_vote 

    has_one :vote, :dependent => :destroy, :as => :votable 

    protected 
    def create_vote 
     self.vote = Vote.create(:score => 0) 
    end 
end 

コメント:あなたは、私が同じコールバックを持って

#models/comment.rb 

class Comment < ActiveRecord::Base 

    after_create :create_vote 

    has_one :vote, :dependent => :destroy, :as => :votable 

    protected 
    def create_vote 
     self.vote = Vote.create(:score => 0) 
    end 
end 

投票(多型)

#models/vote.rb 
class Vote < ActiveRecord::Base 
belongs_to :votable, :polymorphic => true 
end 

を見ることができるように。どのように簡単ですか?私はコールバックでモジュールを作る場合これは正しいですか?

答えて

2

はい、同じ繰り返し可能なメソッドを含むモジュールを定義できますが、そのモジュールが含まれている場合は、すべてのActiveRecordマクロも定義する必要があります。

module VoteContainer 
    def self.included(base) 
    base.module_eval { 
     after_create :create_vote 
     has_one :vote, :dependent => :destroy, :as => :votable 
    } 
    end 

    protected 
    def create_vote 
    self.vote = Vote.create(:score => 0) 
    end 
end 

class Comment < ActiveRecord::Base 
    include VoteContainer 
end 
+0

OK:

は、それは次のようになります。ありがとうございました。私はモジュールを作成します。 – Mike