Rails 中的单独日期和时间表单字段 [英] Separate date and time form fields in Rails

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

问题描述

我有一个带有日期时间列 starts_at 的 ActiveRecord 模型 Event.我想提供一个表格,其中 starts_at 的日期和时间是单独选择的(例如 "23-10-2010" 用于日期和 "18:00" 时间).这些字段应该由单列 starts_at 支持,并且验证也最好针对 starts_at.

I have an ActiveRecord model Eventwith a datetime column starts_at. I would like to present a form, where date and time for starts_at are chosen separately (e.g. "23-10-2010" for date and "18:00" for time). These fields should be backed by the single column starts_at, and validations should preferably be against starts_at, too.

我当然可以处理虚拟属性和钩子,但我想要一个更优雅的解决方案.我已经对 composed_of (rdoc) 和属性装饰器(灯塔讨论, github) 没有成功.

I can of course muck around with virtual attributes and hooks, but I would like a more elegant solution. I have experimented with both composed_of (rdoc), and attribute-decorator (lighthouse discussion, github) without success.

下面是我想要的粗略轮廓..

Below is a rough outline of what I would like..

class Event < ActiveRecord::Base
  validates_presence_of :start_date
end

# View
# On submission this should set start_date.
form_for @event do |f|
  f.text_field :starts_at_date         # date-part of start_date
  f.text_field :starts_at_time_of_day  # time-of-day-part of start_date
  f.submit
end

感谢任何帮助.

推荐答案

今天正在研究一个 Rails 项目,并发现了这个宝石:

Was looking at this today for a Rails project, and came across this gem:

https://github.com/shekibobo/time_splitter

设置日期时间可能是一件困难或丑陋的事情,尤其是通过网络表单.找到一个好的 DatePicker 或 TimePicker 很容易,但让它们同时工作可能很困难.TimeSplitter 自动为您的日期时间或时间属性生成日期、时间、小时和分钟的访问器,这使得使用不同的表单输入来设置日期时间字段的不同部分变得微不足道.

Setting DateTimes can be a difficult or ugly thing, especially through a web form. Finding a good DatePicker or TimePicker is easy, but getting them to work on both can be difficult. TimeSplitter automatically generates accessors for date, time, hour, and min on your datetime or time attributes, making it trivial to use different form inputs to set different parts of a datetime field.

看起来它可以为您完成工作

Looks like it would do the job for you

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

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