在Rails 3中如何使用number_to_phone? [英] How do you use number_to_phone in Rails 3?

查看:78
本文介绍了在Rails 3中如何使用number_to_phone?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将电话号码存储为"1234567890".

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

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

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

谢谢.

推荐答案

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

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

然后您认为

<%= format_phone(phone_number)%>

这篇关于在Rails 3中如何使用number_to_phone?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆