Ruby Forum Ruby on Rails > Model validation

Posted by alex77000@gmail.com (Guest)
on 19.08.2008 18:01
(Received via mailing list)
Hi,

I don't understand the validate method inside the model objet, when
using the fields are always empty ?

class Personne < ActiveRecord::Base
    set_table_name 'personnes'

    has_many :emails

    protected

    def validate
        if nom = ""
            errors.add( "nom", "Le nom ne peut pas etre vide" )
        end
        if prenom = ""
            errors.add( "prenom", "Le prenom ne peut pas etre vide" )
        end
    end

end

Thank you for your help
Posted by Christina B. (christina)
on 19.08.2008 18:19
> 
>     def validate
>         if nom = ""
>             errors.add( "nom", "Le nom ne peut pas etre vide" )
>         end
>         if prenom = ""
>             errors.add( "prenom", "Le prenom ne peut pas etre vide" )
>         end
>     end
> 

You are setting nom equal to blank by using nom = "".  Instead, write 
nom == "" to compare nom to blank.  Of course you'll do the same with 
prenom.
Posted by david (Guest)
on 19.08.2008 21:26
(Received via mailing list)
Hey Alex,

you can use the method "validates_presence_of" to validate the fields
in blank:

class Personne < ActiveRecord::Base
    set_table_name 'personnes'

    has_many :emails

    validates_presence_of :nom, :message => "Le nom ne peut pas etre
vide"
    validates_presence_of :prenom, :message => "Le prenom ne peut pas
etre vide"
end

I hope I help you.

On Aug 19, 6:19 pm, "Christina B." <rails-mailing-l...@andreas-s.net>
Posted by Alexandre Brillant (Guest)
on 20.08.2008 09:08
(Received via mailing list)
Thank you a lot !

No comment about the = and ==, this is the result of working being 
tired...