Rails 4 - 将日期时间转换为单独的日期和时间字段 [英] Rails 4 - Convert datetime into separate date and time fields

查看:27
本文介绍了Rails 4 - 将日期时间转换为单独的日期和时间字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 mysql 日期时间字段转换为两个表单字段(1)仅日期,(2)仅时间,并在表单提交时将这两个字段组合回日期时间格式?

How can you convert a mysql datetime field into two form fields (1) date only, (2) time only, and combine both fields back into datetime format on form submit?

这将允许使用以下 gem,但将日期存储在单个日期时间字段中:

This would allow the use of the following gems, but store the dates in a single datetime field:

gem 'bootstrap-datepicker-rails'
gem 'bootstrap-timepicker-rails'

提前致谢!

推荐答案

在@Althaf 的帮助下找到了解决方案

Found the solution with help from @Althaf

model.rb 添加虚拟属性使用 before_save 回调转换回日期时间.

Added virtual attributes to model.rb Used before_save callback to convert back to datetime.

before_save :convert_to_datetime

def sched_date_field
  sched_date.strftime("%d/%m/%Y") if sched_date.present?
end 

def sched_time_field
  sched_time.strftime("%I:%M%p") if sched_time.present?
end

def sched_date_field=(date)
  # Change back to datetime friendly format
  @sched_date_field = Date.parse(date).strftime("%Y-%m-%d")
end

def sched_time_field=(time)
  # Change back to datetime friendly format
  @sched_time_field = Time.parse(time).strftime("%H:%M:%S")
end

def convert_to_datetime
  self.sched_time = DateTime.parse("#{@sched_date_field} #{@sched_time_field}")
end

使用 Rails 4,需要将 sched_date_field 和 sched_time_field 添加到 controller.rb

Using Rails 4, needed to add sched_date_field and sched_time_field to strong params in controller.rb

这是_form.html.erb

<%= f.label :sched_date_field, "Scheduled Date" %>
<%= f.text_field :sched_date_field, :class => "datepicker" %>

<%= f.label :sched_time_field, "Scheduled Time" %>
<%= f.text_field :sched_time_field, :class => "timepicker" %>

这篇关于Rails 4 - 将日期时间转换为单独的日期和时间字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆