你如何在Rails 3中使用number_to_phone?

B S*_*ven 2 forms ruby-on-rails form-for number-formatting ruby-on-rails-3

我将电话号码存储在数据库中为"1234567890".

你如何使用number_to_phone以"(123)456-7890"的形式很好地显示数字?

我尝试了以下但它只显示了数字.

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

谢谢.

Uch*_*nna 5

你可以在你的应用程序助手中创建一个这样的简单助手

  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
Run Code Online (Sandbox Code Playgroud)

然后在你看来做

<%= format_phone(phone_number)%>
Run Code Online (Sandbox Code Playgroud)