I have a form that creates a new entry into a database. One of the fields uses jquery Datepicker. At the moment, I can pick a date using the UI calendar and it displays in the right format in the textbox, but when I submit the form, the format changes back to the default setting, and saves in the database. I have had this working before on a older version of my site, and I tried following questions already posted, but had no luck. Hopefully someone can see the problem. Thanks.
Here’s part of my Project Controller:
def create
@project = Project.new(params[:project])
@project.client = params[:new_client] unless params[:new_client].blank?
@project.exception_pm = params[:new_exception_pm] unless params[:new_exception_pm].blank?
@project.project_owner = params[:new_project_owner] unless params[:new_project_owner].blank?
@project.role = params[:new_role] unless params[:new_role].blank?
@project.industry = params[:new_industry] unless params[:new_industry].blank?
@project.business_div = params[:new_business_div] unless params[:new_business_div].blank?
respond_to do |format|
if @project.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render json: @project, status: :created, location: @project }
else
format.html { render action: "new" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
Here’s part of my form view:
<%= form_for(@project) do |f| %>
<% if @project.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% @project.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :start_date %><br />
<%= f.text_field :start_date, :class => 'datepicker' %>
</div>
<div class="field">
<%= f.label :end_date %><br />
<%= f.text_field :end_date, :class => 'datepicker' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Here’s my application.js file:
$(function() {
$("#project_start_date").datepicker({dateFormat: 'dd-mm-yy'});
});
$(function() {
$("#project_end_date").datepicker({dateFormat: 'dd-mm-yy'});
});
Thanks in advance!
This probably has nothing to do with the saving of the date, but with the display of the date. Dates are stored in the database as dates, not strings, so when you view the date, it is shown as the default output format after rails converts the type.
In your view, you need to format it with
strftimeor possibly use I18N routines