问题描述
我一直在到处找,但似乎无法找到一个很好的解决方案。
I have been looking everywhere but can't seem to find a good solution for this.
我的窗体有一个日期(文本框用日期选择器)和时间(文本框与timepicker),我想要映射到所谓的模型字段 due_at
。
My form has a date (textfield with datepicker) and a time (textfield with timepicker), which I want to map to an model field called due_at
.
到目前为止,我一直在处理这在我的控制器配有独立的参数加入它为datetime然后设置手动模式领域,但它的混乱和真的认为这个逻辑应存放在模型/视图。
So far I been handling it in my controller with separate parameters to join it up to a datetime then set the model field manually, but it's messy and really think this logic should be kept in model/view.
我希望能够处理两个表单域模型中的一个属性,然后分裂回了错误,执行什么样的标准的编辑操作等,基本上一个自定义的方式 datetime_select 做,但是把我自己的触摸到它。
I would like to be able to handle the two form fields to an attribute in the model, then split it back out for errors, edit action etc. Basically a custom way of performing what the standard datetime_select does, but putting my own touch to it.
有没有东西,我可以把我的模式是怎样的?
Is there something that I can put in my model like ?
def due_at=(date, time)
...
end
我一直在寻找一些地方,却找不到了,你将如何做到这一点。人们说,使用JavaScript来填充隐藏字段,但似乎不喜欢为pretty的简单的问题了干净的解决方案。
I been looking a number of places, but can't find out how you would do this. People say to use javascript to populate a hidden field, but just don't seem like the cleanest solution for a pretty simple problem.
任何意见/帮助将非常AP preciated。
Any advice/help would be much appreciated.
感谢。
推荐答案
第一:请重命名您的字段,因为created_at可能会导致冲突与ActiveRecord的
First: please rename your field because created_at may cause conflicts with ActiveRecord.
我正是这样做与格式M场/ D / YYYY H:M(小时/分钟,在24小时格式)
I did exactly this for a field with the format M/D/YYYY H:M (Hours/Minutes in 24hrs format)
在你的模型:
attr_accessor :due_date, :due_time
before_validation :make_due_at
def make_due_at
if @due_date.present? && @due_time.present?
self.due_at = DateTime.new(@due_date.year, @due_date.month, @due_date.day, @due_time.hour, @due_time.min)
end
end
def due_date
return @due_date if @due_date.present?
return @due_at if @due_at.present?
return Date.today
end
def due_time
return @due_time if @due_time.present?
return @due_at if @due_at.present?
return Time.now
end
def due_date=(new_date)
@due_date = self.string_to_datetime(new_date, I18n.t('date.formats.default'))
end
def due_time=(new_time)
@due_time = self.string_to_datetime(new_time, I18n.t('time.formats.time'))
end
protected
def string_to_datetime(value, format)
return value unless value.is_a?(String)
begin
DateTime.strptime(value, format)
rescue ArgumentError
nil
end
end
现在的观点:
<%= text_field_tag :due_time, I18n.l(@mymodel.due_time, :format => :time) %>
<%= text_field_tag :due_date, I18n.l(@mymodel.due_date, :format => :default) %>
现在在config /区域设置/ en.yml(如果英语)
now in the config/locales/en.yml (if english)
date:
formats:
default: "%m/%d/%Y"
time:
formats:
time: "%H:%M"
您可以改变路线的日期格式。
You may change the date format of course.
这篇关于Rails的多个字段一个模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!