ruby on rails - query phone number with different format in the model -
there's table named "person" attribute id primary key , phone_number user input formatted in different ways. need query id phone number. example, person.where(:phone_number => 4155332321) however, number in model 415-533-2321 or 4155332321. how write query that? btw, can't change phone number format in model. otherwise, can convert phone in query , model same format. thanks
i think you'll need two-part approach this.
first, you'll want save "normalized" phone number database. contains no formatting @ -- numbers. require add new column database, say, normalized_phone_number , write before_save callback store value.
class person   before_save :normalize_phone_number    def self.normalize_number(number)     number.gsub(/[^\d]/, '') if string.present?   end    def normalize_phone_number     self.normalized_phone_number = person.normalize_number(self.phone_number)   end end next, you'll want write custom class method find person based on normalized number user input. person class include:
class person   def self.with_normalized_phone_number(phone_number)     where(normalized_phone_number: normalize_number(phone_number)).first   end end you write person.with_normalized_phone_number activerecord scope, preference, "using class method preferred way accept arguments scopes."
Comments
Post a Comment