你如何在Rails 3中使用number_to_phone?

时间:2011-07-17 19:45:03

标签: ruby-on-rails ruby-on-rails-3 forms form-for number-formatting

我将电话号码存储在数据库中为“1234567890”。

你如何使用number_to_phone在表格中很好地显示数字“(123)456-7890”?

我尝试了以下但是只显示了数字。

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

感谢。

1 个答案:

答案 0 :(得分: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

然后在你的视图中做

<%= format_phone(phone_number)%>