问题
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