B Seven
B Seven

Reputation: 45943

How do you use number_to_phone in Rails 3?

I am storing phone number in database as "1234567890".

How do can you use number_to_phone to display the number nicely in a form as "(123) 456-7890"?

I tried the following but it showed just the numbers.

<%= f.text_field number_to_phone(:phone_number) %>

Thanks.

Upvotes: 2

Views: 3356

Answers (1)

Uchenna
Uchenna

Reputation: 4089

you can create a simple helper like this in your application helper

  def format_phone(phone, mobile=false)
    return phone if format.blank?
    groupings = format.scan(/d+/).map { |g| g.length }
    groupings = [3, 3, 4] unless groupings.length == 3
    ActionController::Base.helpers.number_to_phone(
      phone,
      :area_code => format.index('(') ? true : false,
      :groupings => groupings,
      :delimiter => format.reverse.match(/[^d]/).to_s
    )
  end

then in your view do

<%= format_phone(phone_number)%>

Upvotes: 5

Related Questions