Combine 3 select fields and validate as one in my User model in ruby on rails 3

Posted by Psychonetics on Stack Overflow See other posts from Stack Overflow or by Psychonetics
Published on 2011-06-26T01:30:39Z Indexed on 2011/06/26 8:22 UTC
Read the original article Hit count: 441

Ok I have 3 select boxes for selecting date of birth.

I have constants setup in my User model to provide months, years etc..

Anyway I can successfully validate these select boxes separately.

What I want to do is combine the :day, :month and :year and store in :birthday and validate the whole date as one so I can return 1 error rather than 3 separate ones.

Also doing this will make it easier to store the validated date in my birthday field in my database.

Part of my form

    <td> <%= f.input :day, :required => false, :label => "Birthday: " , :prompt => "Day", :collection => User::DAYS  %></td>
 <td> <%= f.input :month, :label => false, :prompt => "Month", :collection => User::MONTHS %> </td> 
 <td> <%= f.input :year, :label => false, :prompt => "Year", :collection => User::YEAR_RANGE %> </td> 

Part of User model

MONTHS = ["January", 1], ["February", 2], ["March", 3], ["April", 4], ["May", 5], ["June", 6], ["July", 7], ["August", 8], ["September", 9], ["October", 10], ["November", 11], ["December", 12] # finish this DAYS = 1..31 # finish this START_YEAR = Time.now.year - 106 END_YEAR = Time.now.year YEAR_RANGE = START_YEAR..END_YEAR

class User < ActiveRecord::Base attr_accessor :day, :month, :year

validates_presence_of :day, :message => 'What day in a month was you born?'
validates_presence_of :month, :message => 'What month was you born?'
validates_presence_of :year, :message => 'What is your year of birth?'

end

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby