Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I spent some time looking in the code, and changing the DATE_FORMAT won't work because Rails never asks for the date format. Felix's solution of setting :value does work, but feels cumbersome: why should I have to set the value of date-specific textfields by hand? So this is a codesmell, and I wanted something better.</p> <p>Here's my short solution, but then I'll explain it a bit because I'm hoping somebody else will write something better:</p> <pre><code>MyModel &lt; ActiveRecord::Base # ... self.columns.each do |column| if column.type == :date define_method "#{column.name}_before_type_cast" do self.send(column.name).to_s end end end end </code></pre> <p>Somewhat longer explanation: When a textfield is setting the value attribute, it'll first look in the options hash (which is why Felix's solution works), but if it's not there, it'll call <code>form.object.check_in_date_before_type_cast</code>, which (after some method_missing magic) will call <code>form.object.attributes_before_type_cast['check_in_date']</code>, which will look up 'check_in_date' in the @attributes hash inside form.object. My <em>guess</em> is that the @attributes hash is getting the direct MySQL string representation (which follows the 'yyyy-mm-dd' format) before it gets wrapped in a Ruby object, which is why simply setting the DATE_FORMAT doesn't work by itself. So the dynamic method creation above creates methods for all date objects that actually perform the typecast, allowing you to format the date using <code>ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default]</code>.</p> <p>This feels a little dirty because the whole purpose of '_before_type_cast' is to avoid a typecast, and this is one of those "thar be dragons" monkeypatches. But still, from what I can tell, it feels like the best of what's around. Maybe somebody else can do a little more digging and find a better solution?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload