Forum: Ruby on Rails Migration : value between 1 and 7

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Guillaume L. (Guest)
on 2009-02-25 20:49
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!
Philip H. (Guest)
on 2009-02-25 20:54
(Received via mailing list)
>  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
Maurício L. (Guest)
on 2009-02-25 20:55
(Received via mailing list)
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.
Guillaume L. (Guest)
on 2009-02-25 20:56
I'm using mySQL. Can I add a parameter :min and :max?
Maurício L. (Guest)
on 2009-02-25 20:56
(Received via mailing list)
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
Guillaume L. (Guest)
on 2009-02-25 20:57
Ok so I''ll dot it at my model. Thank you!
Guillaume L. (Guest)
on 2009-02-25 21:02
Maurício Linhares wrote:
> Ops, it's a to_a


Why do we need to_a?
Maurício L. (Guest)
on 2009-02-25 21:06
(Received via mailing list)
'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.
Rick (Guest)
on 2009-02-25 21:06
(Received via mailing list)
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-
This topic is locked and can not be replied to.