2014-09-27 25 views
0

在我的模型,我使用一些功能如何使用輔助函數模型Ruby on Rails的3.2.x中

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 

不工作可能需要屬性?

回答

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 

文件,你的模塊將在您的載荷傳輸路徑的地方放置。