Confusion with validates_inclusion_of


#1

It appears that if your trying to use validates_inclusion_of for a
string value allow_nil wont work. For example, if I have an attribute
:year which is stored as a varchar then:

 validates_inclusion_of :year, :in => "1980"..Time.now.year.to_s, 

allow_nil=>true

will successfully validate the range but will not allow an empty input
field to be submitted. However, if :year is stored as an integer then:

 validates_inclusion_of :year, :in => 1980..Time.now.year, 

allow_nil=>true

will validate the range correctly and allow an empty input field to be
submitted.

I guess I’m posting because I think I understand what it’s doing but I
would like a deeper understanding of why this works this way. Can anyone
shed some light for me?

William


#2

If year is a varchar, and the input field is left empty, is the variable
nil or “” ? If it;s “” then allow_nil won’t matter.

A.

William LeFevre wrote:

It appears that if your trying to use validates_inclusion_of for a
string value allow_nil wont work. For example, if I have an attribute
:year which is stored as a varchar then:

 validates_inclusion_of :year, :in => "1980"..Time.now.year.to_s, 

allow_nil=>true

will successfully validate the range but will not allow an empty input
field to be submitted. However, if :year is stored as an integer then:

 validates_inclusion_of :year, :in => 1980..Time.now.year, 

allow_nil=>true

will validate the range correctly and allow an empty input field to be
submitted.

I guess I’m posting because I think I understand what it’s doing but I
would like a deeper understanding of why this works this way. Can anyone
shed some light for me?

William


#3

That was my assumption but it was late so I didn’t turn on breakpointer
and dig deeper.

Alan F. wrote:

If year is a varchar, and the input field is left empty, is the variable
nil or “” ? If it;s “” then allow_nil won’t matter.

A.