[LRUG] How does Rails decide how to parse ambiguous dates?

John Winters john at sinodun.org.uk
Tue Jul 26 08:07:51 PDT 2011


On 26/07/11 15:53, Jordi Noguera Leon wrote:
> You can specify the formats for your dates in
> config/initializers/time.rb with:
>
> Date::DATE_FORMATS[:default] = "%d/%m/%y"
> Date::DATE_FORMATS[:whatever] = "%y-%m-%d"
>
> (Date::DATE_FORMATS or Time::DATE_FORMATS depending on whether you're
> dealing with Date objects or Time objects)
>
> Then, @date.to_s should do what you're expecting and you could do
> @date.to_s(:whatever)

Yes, already got that far, but that isn't addressing the question asked.

The question is, how to get a date formatted in a particular way into a 
text_field (in order to use JQuery-UI's datepicker to handle date input).

I've been digging a bit further, and I think I've now got an answer.

As far as I can see, Rails does absolutely *no* conversion of dates in 
going from the internals of your model to a text_field.  The contents 
for the field is extracted from your model by calling:

<model>.<date_field>_before_type_cast

and that in turn is indirected into read_attribute_before_type_cast 
which consists (in toto) of:

   def read_attribute_before_type_cast(attr_name)
     @attributes[attr_name]
   end

Unless I've missed it somewhere, no formatting at all occurs.

The briefest way I've therefore come up with is to invoke text_field 
like this:

   <div class="field">
     <%= f.label :starts_at %><br />
     <%= f.text_field :starts_at, :value => @era.starts_at.to_s %>
   </div>

assuming you've got your default format set the way you want it, or 
otherwise call to_formatted_s(:whatever).

I'm open to correction if I've missed a formatting layer somewhere, but 
I don't think there is one.

Cheers,
John



More information about the Chat mailing list