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

ご覧のとおり、同じコールバックがあります。どうすれば簡単ですか?コールバック付きのモジュールを作成した場合、これは正しいですか?

4

1 に答える 1

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
于 2012-03-11T11:06:02.543 に答える