ruby-on-rails - 简化模型中的代码

标签 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

正如你所看到的,我有相同的回调。怎么比较容易呢?如果我制作一个带有回调的模块,这是正确的吗?

最佳答案

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

关于ruby-on-rails - 简化模型中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9654215/

相关文章:

javascript - ClickAwayListener 的回调函数在执行中途停止

ruby-on-rails - 将 bootstrap span 放入 haml 链接内

css - Ruby on Rails 导入 Bootstrap 未找到

PostgreSQL 的 Django 模型继承错误

cocoa - 在 Cocoa 中正确设计模型 Controller ?

node.js - 将回调传递给以await 为前缀的函数。执行顺序

javascript - 如果回调被阻止,setInterval 的不同行为

javascript - rails 中的自动完成

ruby-on-rails - 在 rails 3 中查找没有关联记录的记录

ruby-on-rails - Rails 4 用户之间的积分交换