如何将mysql datetime字段转换为两个表单字段(1)仅限日期,(2)仅限时间,并将两个字段组合为表单提交后的日期时间格式?Rails 4 - 将日期时间转换为单独的日期和时间字段
这将允许使用下面的宝石,但日期存储在一个日期时间字段:
gem 'bootstrap-datepicker-rails'
gem 'bootstrap-timepicker-rails'
提前感谢!
如何将mysql datetime字段转换为两个表单字段(1)仅限日期,(2)仅限时间,并将两个字段组合为表单提交后的日期时间格式?Rails 4 - 将日期时间转换为单独的日期和时间字段
这将允许使用下面的宝石,但日期存储在一个日期时间字段:
gem 'bootstrap-datepicker-rails'
gem 'bootstrap-timepicker-rails'
提前感谢!
发现帮助解决从@Althaf
添加的虚拟属性model.rb 用于before_save
回调转换回日期时间。
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添加到严格PARAMS需要
下面是字段_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" %>
如果您有专业订阅the revised one,您可以使用虚拟属性See this Railscast。
基本上在视图中,您将以下
<%= f.label :date_field %>
<%= f.text :date_field %>
<%= f.label :time_field %>
<%= f.text :time_field %>
你的数据库将仍然保持了场,我会打电话给full_date
现在,在你的模型,你必须定义上述2个领域如下。
def date_field # What this returns will be what is shown in the field
full_date.strftime("%m-%d'%y") if full_date.present?
end
def time_field
full_date.strftime("%I:%M%p") if full_date.present?
end
def time_field=(time)
full_date = DateTime.parse("#{date_field} #{time_field})
end
由于看起来您正在使用Rails 4,因此您必须在强参数中允许使用date_field和time_field。
你可以使用date_time_attribute gem:
class MyModel < ActiveRecord::Base
include DateTimeAttribute
date_time_attribute :scheduled_at
end
它将允许您分别设置schedule_at_date
和scheduled_at_time
。一旦设置了属性,数值将被合并到schedule_at
中。
严格的参数,你的意思是“强烈的参数”?此外,这段代码似乎在sched_time上引发了一个未定义的变量错误。 –
这是一个边缘情况,但是如果你使用这种技术并且需要对'sched_time'字段进行任何验证,它将会失败。你可以尝试把'before_save'改成'before_validation'。但是,如果你有级联验证,这可能会失败。在这个简短的评论中有点难以解释,但相信我,它会失败。 – Karl
@Karl你推荐什么?我遇到了这个问题..我想改变我的数据模型,将日期,时间和时区存储为3个单独的字段。 – Turgs