Search code examples
ruby-on-railsvalidationcustom-validators

Need a piece of code #rails 3 (custom validations)


I want to show an error message like "date of joining is Invalid" if the "date of joining" is before the "date of birth"(it doesnt happen in real.. but i want it).

Please suggest me with a piece of code.


Solution

  • i think you have a user model whith date_of_birth attribute , date of joining is the date when you save your user, and Active Record create automatically for you an attribute "created_at" for each object you save in database.

    so you can consider "created_at" like date_of_join.

    the next step is to add a validate method to your user model like this :

    class User < ActiveRecord::Base
     #attr_accessible :date_of_birth, ( etc ...... )
     #.....
     #.....
     validate  :date_of_join_must_be_great_than_birth
     #.....
     #.....
     private
    
         def date_of_join_must_be_great_than_birth
           errors.add(:date_of_birth, "date of birth is greater than date of joining" ) unless date_of_birth < created_at
         end
    
     end
    

    each time you save or you update your user, validate method is invoked

    you can also learn about filter methods in rails , i hope this can help you