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!

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

Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)

On Wed, Feb 25, 2009 at 3:49 PM, Guillaume L.

I’m using mySQL. Can I add a parameter :min and :max?

Ops, it’s a to_a

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

Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)

On Wed, Feb 25, 2009 at 3:54 PM, Maurício Linhares

Ok so I’'ll dot it at my model. Thank you!

'Cos:

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

Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)

On Wed, Feb 25, 2009 at 4:02 PM, Guillaume L.

Maurício Linhares wrote:

Ops, it’s a to_a

Why do we need to_a?

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

On Feb 25, 8:49 am, Guillaume L. <rails-mailing-l…@andreas-