Forum: Ruby on Rails confusion with validates_inclusion_of

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.
C56f6508ce4610e8527606a435b5870f?d=identicon&s=25 William Lefevre (wlefevre)
on 2006-02-14 09:59
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
4daf0b71d5d9a3882e583c0e72eaf5dc?d=identicon&s=25 Alan Francis (Guest)
on 2006-02-14 13:01
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
C56f6508ce4610e8527606a435b5870f?d=identicon&s=25 William Lefevre (wlefevre)
on 2006-02-14 17:20
That was my assumption but it was late so I didn't turn on breakpointer
and dig deeper.

Alan Francis 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.
>
This topic is locked and can not be replied to.