简化模型中的代码

时间:2012-03-11 10:36:46

标签: ruby-on-rails model callback rails-models

我有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 个答案:

答案 0 :(得分: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