2

I have 3 models and polymorphic relationships. Post:

#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

Comment:

#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

Vote (polymorphic)

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

As you can see I have the same callbacks. How does it easier? If i make a module with callback this correct?

Mike
  • 1,042
  • 1
  • 8
  • 14

1 Answers1

2

Yes, you can define a module containing the same repeatable methods, but you would also have to define all the ActiveRecord macros when that module is included.

It might look something like this:

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
sinjed
  • 906
  • 7
  • 10