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?
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: