如何在time_select视图助手中设置时间? [英] How do I set a time in a time_select view helper?

查看:109
本文介绍了如何在time_select视图助手中设置时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个time_select,试图在其中设置时间值,如下所示;

I have a time_select in which I am trying to set a time value as follows;

<%= f.time_select :start_time, :value => (@invoice.start_time ? @invoice.start_time : Time.now) %>

这总是产生一个带有当前时间的时间选择器,而不是@ invoice.start_time的值.

This always produces a time selector with the current time rather than the value for @invoice.start_time.

@ invoice.start_time实际上是一个datetime对象,但是如果我使用的话,它也可以传递给时间选择器

@invoice.start_time is in fact a datetime object but this is passed to the time selector just fine if I use

<%= f.time_select :start_time %>

我想我真正要问的是如何在time_select助手中使用:value选项.如下所示的尝试似乎无法产生预期的结果;

I guess what I'm really asking is how to use the :value option with the time_select helper. Attempts like the following don't seem to produce the desired result;

<%= f.time_select :start_time, :value => (Time.now + 2.hours) %>
<%= f.time_select :start_time, :value => "14:30" %>

推荐答案

@ invoice.start_time是否已分配值?我猜不是. 如果您使用该代码,@ invoice.start_time将返回nil,因此:value始终默认为Time.now.这里的问题是您正在使用的条件语句.我假设在尝试创建新数据时会发生这种情况.填写表单时,@ invoice.start_time不会填充任何值.因此,直到您保存之前,它始终为零.

Has @invoice.start_time have a value assigned to it? I guess not. @invoice.start_time will return nil if you use that code.. and hence the :value will always default to Time.now. The problem here is the conditional statement that you are using. I am assuming this is happening when you try to create new data. When you filling up the form, @invoice.start_time is not filled with any value. Hence its nil throughout till you save.

我建议您将代码更改为:

I would suggest that you change the code to:

<%= f.time_select :start_time, :value => @invoice.start_time, :default => Time.now %>

实际上,如果您想更清楚地知道自己想要的time_select辅助对象做什么,那么这将使事情变得更容易.

Actually if you could be more clear in your question as to what you want your time_select helper to do then it would make things easier.

这篇关于如何在time_select视图助手中设置时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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