【问题标题】:Simplify the code in models简化模型中的代码
【发布时间】:2012-03-11 10:36:46
【问题描述】:

我有 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

如您所见,我有相同的回调。怎么更容易?如果我制作一个带有回调的模块,这个正确吗?

【问题讨论】:

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


    【解决方案1】:

    是的,您可以定义一个包含相同可重复方法的模块,但是当包含该模块时,您还必须定义所有 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
    

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 1970-01-01
      • 2011-08-09
      • 2014-12-28
      • 2012-05-11
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多