使用simple_form格式化日期输入

ser*_*erg 10 html ruby-on-rails date input simple-form

date我的数据库中有一个类型字段.

这是我正在使用的视图代码:

# Using 'as: :string' to avoid those three dropdowns rails generates.
= f.input_field :start_date, as: :string, class: 'form-control datepicker'
Run Code Online (Sandbox Code Playgroud)

保存日期时,我使用一个显示日历的jquery插件,并写入如下日期:11/05/2013.

但是,在编辑同一记录时,输入会填充一个值2013-05-11.

我怎样才能使它如此simple_form实际上尊重我定义的日期格式en.yml

rb5*_*512 30

这就是你需要的:

f.input :my_date,
        :as => :string, 
        :input_html => { :value => localize(f.object.my_date) }
Run Code Online (Sandbox Code Playgroud)

PS:这是谷歌搜索中的第一个链接:)

  • 什么搜索词 (5认同)
  • 还值得知道你可以指定localize函数的格式,例如`localize(f.object.my_date,format :: short)` (4认同)
  • 现在*this*是我谷歌搜索中的第一个链接.:) (3认同)

Mat*_*lly 9

我创建了这个类,这样可以很容易地做到这一点:

f.input :my_date, :as => :date_picker
Run Code Online (Sandbox Code Playgroud)

将此类添加到lib /文件夹中并确保包含它(或将其配置为自动加载):

class DatePickerInput < SimpleForm::Inputs::StringInput
  def input
    value = @builder.object.send(attribute_name)
    input_html_options[:value] = case value
                                   when Date, Time, DateTime
                                     format = options[:format] || :medium
                                     value.to_s(format)
                                   else
                                     value.to_s
                                 end

    input_html_options[:class] ||= []
    input_html_options[:class] << "date_picker_input"
    @builder.text_field(attribute_name, input_html_options)
  end
end
Run Code Online (Sandbox Code Playgroud)