【问题标题】:How do you use number_to_phone in Rails 3?你如何在 Rails 3 中使用 number_to_phone?
【发布时间】:2011-07-17 19:45:02
【问题描述】:

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

如何使用 number_to_phone 以“(123) 456-7890”的形式很好地显示号码?

我尝试了以下方法,但它只显示了数字。

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

谢谢。

【问题讨论】:

  • 如果你在表单中使用助手,它会弄乱数据
  • 只需按原样保存数字并使用助手对其进行格式化..就像下面的答案

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多