Rails 3 jquery date picker date not saving to database

后端 未结 6 1912
独厮守ぢ
独厮守ぢ 2020-12-31 02:21

When I submit my form I can see the date being sent to in the post. However, It doesn\'t save the date. If I do a date check it says it is not in the proper format. Here

相关标签:
6条回答
  • 2020-12-31 02:37
    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]);
      }
    });
    
    0 讨论(0)
  • 2020-12-31 02:40

    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
    
    0 讨论(0)
  • 2020-12-31 02:44

    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.

    0 讨论(0)
  • 2020-12-31 02:49

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

    0 讨论(0)
  • 2020-12-31 02:52

    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!

    0 讨论(0)
  • 2020-12-31 02:59

    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...

    0 讨论(0)
提交回复
热议问题