简体   繁体   中英

How to use helper function in model Ruby on Rails 3.2.x

In my model I'm using some function

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

I would like to use it in different model, so it would be a good idea to put this function to the application_helper and then call this function in model? If yes can anyone please explain to me how to do it?

I try tu put in my helper

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

But then how to call it in model?

before_validation :normalize_account

Does't work probably need attribute?

You don't want to use ApplicationHelper for this - it is rather reserved for a methods to be used in view. What you want is to create a module and include it into models which need those method:

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

File with your module needs to be placed somewhere in your load paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM