如何在模型Ruby on Rails 3.2.x中使用辅助函数

时间:2014-09-27 23:53:50

标签: ruby-on-rails ruby ruby-on-rails-3

在我的模型中,我正在使用一些功能

def normalize_account
    self.bacc = bacc.gsub(/[^0-9]/, "") if attribute_present?("bacc")
end

我想在不同的模型中使用它,所以将这个函数放到application_helper然后在模型中调用这个函数是个好主意? 如果有,可以请任何人向我解释如何做到这一点吗?

我试着把我的帮手

放进去
 def normalize_account (accountnum)
  self.accountnum = accountnum.gsub(/[^0-9]/, "") if attribute_present?("accountnum")
end

但是如何在模型中调用它?

before_validation :normalize_account

不起作用可能需要属性吗?

1 个答案:

答案 0 :(得分:2)

您不希望为此使用ApplicationHelper - 它相当于在视图中使用的方法。你想要的是创建一个模块并将其包含在需要这些方法的模型中:

module Normalizer
  module ClassMethods
    def normalize_number(attribute)
      before_validation do
        self[attribute].gsub!(/[^0-9]/, "") unless self[attribute].nil?
      end
    end
  end

  def self.included(mod)
    mod.extend ClassMethods
  end
end

class Model1 < ActiveRecord::Base
  include Normalizer
  normalize_number :accountnum
end

class Model2 < ActiveRecord::Base
  include Normalizer
  normalize_number :bacc
end

需要将包含模块的文件放在加载路径中的某个位置。