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

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

问题描述

我有一个ActiveRecord模型事件与datetime列 starts_at 。我想提交一个表单,其中分别选择 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.

我当然可以使用虚拟属性和钩子,但我想要一个更优雅的解决方案。我已经尝试了 comp_of rdoc )和attribute-decorator(灯塔讨论 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.

以下是我想要的大纲。

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自动生成datetime或时间属性的日期,时间,小时和分钟的访问器,使用不同的窗体输入来设置datetime字段的不同部分。

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天全站免登陆