Rails 3 jquery date picker date not saving to database

£可爱£侵袭症+ 提交于 2019-11-30 08:25:25

I ran into the same issue. One solution is to simply change the format that the datepicker uses:

// in your javascript...
$j(function(){
  $j("#mile_date").datepicker({
    dateFormat: "yy-mm-dd"
  });
});

Rails seems to be able to handle the yy-mm-dd format - I'm using that and am having no issues saving the date to the database. The only issue here is that some might find the yy-mm-dd format a little less good looking than mm/dd/yyyy...

As noted by @BaronVonBraun above rails doesn't seem to handle that format. Changing it as he suggested worked. However, for those wanting a different format than yy-mm-dd you can use the following. The user sees the format you want while rails gets the format it needs.

$j(function(){
    $j("#show_date").datepicker({altField: '#mile_date', altFormat: 'yy-mm-dd'});
});

The show_date is the id of the field they see and the mile_date is a hidden field with the date rails needs.

Here is the documentation.

If anyone is using the jquery_datepicker gem , you'll want to use something similar to the following code in your rails view.

<%= form.hidden_field(:ship_date, :id => "ship_date") %>   
<%= datepicker_input(:show_date, item.id, :size => 10, altField: "#ship_date", altFormat: 'yy-mm-dd', :value => item.ship_date.strftime("%m/%d/%Y"))%>

You can also use form.datepicker_input to attach the the date picker directly to the form, but in my use case, I wanted the date picker to reflect the localized date, which Rails would not accept. So I added a hidden form element and set the alternate field to it, works perfectly!

Or try the delocalize gem: https://github.com/clemens/delocalize

j('.jquery-calendar').datepicker().each(function(){
  // convert dates from db to US format
  var $input = j(this)
  var found = $input.val().match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if(found){
    $input.val(found[2]+'/'+found[3]+'/'+found[1]);
  }
});

Kinda of hacky but made a helper the set things straight when I know I am giving the server dates in the mm-dd-yy format

def convert_to_y_m_d(date)
  new_date = date.split("-")[2] + "-" + date.split("-")[0] + "-" + date.split("-")[1]
  new_date
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!