2012-03-11 80 views
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 

正如你可以看到我有同樣的回調。它如何更容易?如果我用回調製作模塊,這是正確的嗎?

回答

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 
+0

確定。謝謝。我將創建該模塊。 – Mike 2012-03-11 11:41:32