Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Human-friendly date format for text_field

I have a birth_date field that is stored as a datetime value. The default rails form helpers spit out a not-too-friendly format, e.g. "2008-06-10 22:33:19.000000". The below is the vanilla rails way.

<div class="field">
  <%= f.label :birth_date %>
  <%= f.text_field :birth_date, :size=>"20" %>
</div>

How can I simply apply a format? I tried various approaches, for example strftime should work, I thought. But when I try the following, I get an error undefined method 'strftime' for nil:NilClass

<div class="field">
  <%= f.label :birth_date %>
  <%= f.text_field :birth_date, :value=>f.object.birth_date.strftime('%m/%d/%Y'), :size=>"20" %>
</div>

Based on some other questions/answers, I tried the following. It works for non-null values, but it is ugly code, and it doesn't work for blank values (actually it shows today's date).

<div class="field">
  <%= f.label :birth_date %>
  <%= f.text_field :birth_date, :value=> Time.parse(f.object.birth_date.to_s).strftime('%m/%d/%Y'), :size=>"20" %>
</div>

In playing around, it seems that outputting f.object.birth_date is treated as a date, rather than datetime. However, when displayed in the text_field (original, ugly formatting), it includes the time. It is friday afternoon, and my combined lack of familiarity with rails forms and ruby date/time objects is making me feel foolish.

Any simple way to get my form to display nothing if null/blank, and a friendly date otherwise?

like image 221
Ben Morris Avatar asked Oct 21 '11 20:10

Ben Morris


2 Answers

If you want a blank string if birth_date is empty, you should simply check that birth_date is non-nil beforehand:

<%= f.text_field :birth_date, :value => (f.object.birth_date.strftime('%m/%d/%Y') if f.object.birth_date), :size => "20" %>

This way, when birth_date is nil, :value gets set to nil.

like image 154
Claw Avatar answered Nov 15 '22 05:11

Claw


Have you tried using the date_select form builder helper method? You can also use datetime_select, but it looks like you just want to work with the date here.

<div class="field">
  <%= f.label :birth_date %>
  <%= f.date_select :birth_date %>
</div>

The API docs are here: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select Add on the options you need.

I've always used that approach, or a javascript date selector like this one from jQuery UI. There are plugins for most JS frameworks these days.

If it MUST be a text_field, use a human language date parsing library like chronic. It'll work, but will require that you parse the input from the form somewhere before applying the attribute to your object.

like image 3
Matthew Lehner Avatar answered Nov 15 '22 04:11

Matthew Lehner