4

We have two columns which require to be declared as t.integer size(1) and size(2). i.e. a max size of 1 (i.e upto 9) and max size of 2 (i.e upto 99). How should I declare this in my migration script.

Joe
  • 14,513
  • 28
  • 82
  • 144
  • I tend to agree with Chris Lewis below. Is the requirement specifying the range of values allowed for the fields [0..9], and [0..99], which can be left to the model to enforce, or is it truly trying to enforce storage bytes? <- crazy talk for an integer column IMO. – railsdog Nov 21 '12 at 17:31
  • I agree -- I am not sure what use-case would require the actual storage of an integer to have a size. If the requirement is to maintain consistency in your data, generally best to let Rails do the work. Or you could do a stored procedure or check constraint in your database (which I would only recommend if some other process is writing to your database, which I would *not* recommend). – Tom Harrison Nov 21 '12 at 18:49

2 Answers2

18

Do you mean that the value in that column should be restricted to the range 1-99?

Having created an integer column you could add ActiveRecord validation to the model:

validates_numericality_of :field_name, :in => 1..99
Chris Lewis
  • 1,315
  • 10
  • 25
-7

You should be able to set a :limit on your migration record. Check the documentation here -- http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column

Ex: add_column :my_tbl, :myint, :integer, :limit => 9

This will set a column length -- in other words, it will only allow integers up to 9 digits long.

If you want to restrict the data input for this column, you'll need to do validations in your model. Have a look at http://guides.rubyonrails.org/active_record_validations_callbacks.html#length

imgrgry
  • 628
  • 1
  • 5
  • 11