Search code examples
ruby-on-railssimple-form

simple_form date input not as select


I use simple_form and I need date select as 3 separate input fields (day month year).

This is what I've got, but it is definitely not what I want.

<%= f.date_select :date_of_birth, start_year: Date.today.year - 16,
                            end_year: Date.today.year - 100,
                            order: [:day, :month, :year], label: false %>

Thanks for help!

As of now, I just assume I will have to substitute my date_of_birth with 3 fields in DB and simply write a method which will assemble these into actually date of birth, which I see as ugly path and hoped there is better one.


Solution

  • I've decided to just add 3 fields to database:

      t.integer :birth_day
      t.integer :birth_month
      t.integer :birth_year
    

    write some validations:

      validates :birth_day, 
                numericality: { only_integer: true, message: "Please enter numbers only." }, 
                length: { is: 2, message: "Should be 2 digits." },
                inclusion: { in: 1..31, message: 'should be in range 1..31'}
      validates :birth_month, 
                numericality: { only_integer: true, message: "Please enter numbers only." }, 
                length: { is: 2, message: "Should be 2 digits." },
                inclusion: { in: 1..12, message: 'should be in range 1..31'}
      validates :birth_year, 
                numericality: { only_integer: true, message: "Please enter numbers only." }, 
                length: { is: 4, message: "Should be 4 digits." },
                inclusion: { in: 1900..1996, message: 'should be in range 1900..1996'}
    

    and write a method to a method assembling a date object:

      def date_of_birth
        "#{birth_day}/#{Date::MONTHNAMES[birth_month]}/#{birth_year}".to_date
      end