How do you use number_to_phone in Rails 3?

流过昼夜 提交于 2019-12-06 10:03:13

问题


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.


回答1:


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)%>


来源:https://stackoverflow.com/questions/6726316/how-do-you-use-number-to-phone-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!