2

我正在尝试将我的 rails 模型的日期字段呈现为日期选择器。

模型看起来像:

class Appointment
  include Mongoid::Document
  field :date, type: Date  
end

_form.html.haml 视图如下所示:

= form_for @appointment, :url => {:action => :create} do |f| 
  = f.text_field(:date, {:class => 'datepicker'})
  %button{:type => 'submit'} Book appointment

:javascript
    jQuery(document).ready(function($) {
      $('.datepicker').datepicker();
    });

控制器动作如下所示:

class AppointmentsController < ApplicationController
  def create
    @appointment = Appointment.new(params[:appointment])

    # rest left out for demo purposes
  end
end

当“new”获取时,调用发生错误:

ArgumentError in AppointmentsController#create

argument out of range

我知道该值发布为 MM/DD/YYYY,即 2013 年 3 月 11 日

如何告诉 Rails 如何正确序列化该字段?

4

3 回答 3

2

我参加聚会有点晚了,但是...

Mongoid 对您作为日期提供的字符串的格式非常特别。据我了解,只有 dd-mm-yyyy 可以。幸运的是,jQuery UI 日期选择器为您提供了格式化其输出的选项。Mongoid 想要的格式如下所示:

$('.datepicker').datepicker({ dateFormat: 'dd-mm-yy' });

有关 datepicker 选项和格式的更多信息:

http://api.jqueryui.com/datepicker/#option-dateFormat

干杯!

于 2013-03-01T06:08:34.313 回答
1

弄清楚了。我添加了另一个字段 date_string 作为 attr_accessor,它不会存储在 db 中但可以显示在表单中,并可用于转换为内部日期字段。模型改为:

class Appointment
  # extend these two to get accesss to drop down options
  include Mongoid::Document
  before_validation :parse_date_if_not_null

  #person info
  field :date, type: Date

  attr_protected :date
  attr_accessor :date_string

  def parse_date_if_not_null
    unless self.date_string.nil? || self.date_string == ''
      self.date = Date.strptime self.date_string, '%m/%d/%Y'
    end
  end
end

在视图中,使用了 date_string 字段:

= form_for @appointment, :url => {:action => :create} do |f| 
  = f.text_field(:date_field, {:class => 'datepicker'})
  %button{:type => 'submit'} Book appointment

:javascript
    jQuery(document).ready(function($) {
      $('.datepicker').datepicker();
    });

这工作正常,我已经验证该字段在数据库中正确设置。

于 2013-01-25T17:19:32.563 回答
0

问题是 rails/activerecord 期望日期为 ISO 格式“yyyy-mm-dd”。但这不是一种用户友好的格式

我认为最简单的解决方案是在 datepicker 上使用 alt 属性 - 基本上,显示日期格式但提交另一种日期格式:

  = f.text_field :your_date, id: "your_date", class: "hidden" // This is hidden
  // This will show up
  = text_field_tag "date[something_we_will_not_use]", f.object.your_date.strftime("%m/%d/%Y"),
    class: "datepicker", 'data-alt-field' => '#your_date'

日期选择器初始化

$('.datepicker').each(function() {

      var alt_field = $(this).attr('data-alt-field');

      $this.datepicker({
        dateFormat: "mm/dd/yy",
        prevText: '<i class="fa fa-chevron-left"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
        altField: alt_field, // This is the tag where the date will be filled
        altFormat: "yy/mm/dd" // This is how the date will be posted to your controller
      });
    })
于 2014-02-20T07:49:51.790 回答