Упростить код в моделях - PullRequest
       16

Упростить код в моделях

2 голосов
/ 11 марта 2012

У меня 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

Как видите, у меня такие же обратные вызовыКак это проще?Если я сделаю модуль с обратным вызовом это правильно?

1 Ответ

2 голосов
/ 11 марта 2012

Да, вы можете определить модуль, содержащий те же повторяемые методы, но вам также потребуется определить все макросы 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
...