Migration : value between 1 and 7

Hello everyone!

I want to add a column to a table. So here is my migration. My question is : Is it possible to say that this value must be between 1 and 7 and must no be a float (1.4 shouldn't be possible) ?

class AddValueToTable < ActiveRecord::Migration   def self.up     add_column :table, :value, :int   end

  def self.down     remove_column :table, :value   end end

Thank you for your help!

I want to add a column to a table. So here is my migration. My question is : Is it possible to say that this value must be between 1 and 7 and must no be a float (1.4 shouldn't be possible) ?

class AddValueToTable < ActiveRecord::Migration def self.up    add_column :table, :value, :int end

def self.down    remove_column :table, :value end end

Well, if you define the column as an integer you'll never end up with 1.4 as a value. It will always get truncated to an integer. Depending on your database you can add those types of restrictions. I don't think rails migrations has support for it directly though.

You could also do it as a before_save validation in the model. You'll probably want to do this anyway so that if a user enters "1.4" you can complain early.

-philip

This isn't someithing to be done inside a migration, but at your model as a validation:

class Table   validates_inclusion_of :value, :in => (1..7).to_i end

Ops, it's a to_a

class Table validates_inclusion_of :value, :in => (1..7).to_a end

Maurício Linhares wrote:

Ops, it's a to_a

Why do we need to_a?

'Cos:

(1..7).include?( 2.2 ) is true, but (1..7).to_a.include?( 2.2 ) isn't.

Add to model

validates_numericality_of :value,   :only_integer => true,   :less_than_or_equal_to => 7,   :greater_than_or_equal_to => 1

to get the inclusive [1-7] int only