I’ve got a form set up for a workout scheduler. I’m using show_date to format the date in a user friendly way, and the actual date field to store the rails-friendly date. When I look at the page, I don’t see anything in the show_date field, though date is still working as expected.
#workout.rb
class Workout < ActiveRecord::Base
validates_presence_of :name
validates_presence_of :show_date
validates_presence_of :time
attr_accessor :show_date
end
#_form.html.erb
<%= simple_form_for @workout, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.input :name %>
<%= f.input :date, :as => :hidden%>
<%= f.input :show_date, :as => :date_picker, :label => 'Date', :input_html => { :value => @workout.date } %>
<%= f.input :time, :minute_step => 15 %>
<div class="form-actions">
<%= f.button :submit, :class => 'btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
workouts_path, :class => 'btn' %>
</div>
<% end %>
#date_picker_input.rb
class DatePickerInput < SimpleForm::Inputs::Base
def input
@builder.text_field(attribute_name, :class => 'date_picker')
end
end
#datepicker.js
$("input.date_picker").datepicker(
{
dateFormat: "mm/dd/yy",
altField: "#workout_date",
altFormat: "dd/mm/yy"
}
);
I’m putting this here instead of in the comments so its easier to see for other people.
You already have the date object in the date field, all you need is to change how it is presented to the user and to do that you should be using a method.
I would change the show_date to be a method that properly formats the date for viewing using strftime. date.strftime(“%m/%d/%Y”) will give you a string formatted into month/day/full_year i.e. “05/01/2012”. http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime has the documentation for the different formatting strings.