0

I have contact_number in my customers table using the field integer. I tried creating a record in rails c but apparently it can't store a larger field of numbers. I looked around online I think I should use float instead of integer given a precision of 10 numbers like in the states

my thought is to create a new migration with

class ChangeContactNumberInCustomerTableToFloatFromInteger < ActiveRecord::Migration
  def change_table 
    remove_column :customers, :contact_number, :integer
    add_column :customers, :contact_number, :float
  end
end

how do I specify the precision and is this the correct way in doing this?

1
  • 3
    Do not store telephone numbers as float. This type has limited precision. @Teeg's suggestion of storing as string make sense. Commented Aug 13, 2013 at 19:30

2 Answers 2

6

First off, if I am correct that contact_number is a phone number, you will want to use a string rather than a numeric field. Phone numbers are not so much numeric values as they are a collection of digits. Or stated more generally, they are a collection of characters, which just happen to be limited to only numbers.

Additionally, it will be easier to parse the area code and country code too, if that is relevant (however hypothetically if you do need to parse country and area code, you'd want to store those in separate columns anyways, but that's a different discussion)

To answer your question directly, use the change_column method instead, like so:

change_column :customers, :contact_number, :string

Details found here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Sign up to request clarification or add additional context in comments.

2 Comments

this answers my question well, I wasn't sure which type to use for my field
@Jngai1297 Glad to hear it. Please click the check mark on whichever answer helped you the most to accept.
2
limit Sets the maximum size of the string/text/binary/integer fields
precision Defines the precision for the decimal fields
scale Defines the scale for the decimal fields
polymorphic Adds a type column for belongs_to associations

here is an example:

class AddDetailsToProducts < ActiveRecord::Migration
  def change
    add_column :products, :price, precision: 5, scale: 2
    add_reference :products, :user, polymorphic: true, index: true
  end
end

from the docs: http://guides.rubyonrails.org/migrations.html

and here are the types of filed you columns can accept:

http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.