Rails: confirm that all fields in the date_select element have been selected but still set: prompt to true

When using Rails date_select with: prompt => true I see a very strange behavior when submitting a form without all the fields selected. For example.

Submitting the form with the selected Jan., but the day and year fields, remaining by default by invitation, lead to January 1, 0001, when they pass the model check. If the test fails and the form is displayed again, January is still selected (correct), but the day is set to 1 (incorrect). If the form is submitted only with the selected year, then the month and day will be set to 1.

This is a very strange behavior - can anyone give me a workaround?

+3
source share
1

. (.. written_at). Date_select { 'written_at(1)' => '2009', 'written_at(2)' => '5', 'written_at(3)' => '27' } . Active records Date .

, Date , Date.new(2009, 0, 1). Rails Time. Rails , . 1.

, written_at Date Time . , written_at_before_time_cast.

: written_at_year, written_at_year= written_at_year_before_type_cast ( , ). before_validation write_at.

class Event < ActiveRecord::Base
  before_validation :reconstruct_written_at

  def written_at_year=(year)
    @written_at_year_before_type_cast = year
  end

  def written_at_year
    written_at_year_before_type_cast || written_at.year
  end

  def written_at_year_before_type_cast
    @written_at_year_before_type_cast
  end

  private

  def reconstruct_written_at
    written_at = Date.new(written_at_year, written_at_month, written_at_day)
  rescue ArgumentError
    written_at = nil
  end
end
+3

Source: https://habr.com/ru/post/1709089/


All Articles