如何在 time_select 视图助手中设置时间?
我有一个 time_select,我试图在其中设置一个时间值,如下所示;
<%= f.time_select :start_time, :value => (@invoice.start_time ? @invoice.start_time : Time.now) %>
这始终会生成一个带有当前时间的时间选择器,而不是 @invoice.start_time 的值。
@invoice.start_time 实际上是一个日期时间对象,但是如果我使用它,它就会传递给时间选择器,
<%= f.time_select :start_time %>
我想我真正要问的是如何将 :value 选项与 time_select 帮助器一起使用。像下面这样的尝试似乎没有产生预期的结果;
<%= f.time_select :start_time, :value => (Time.now + 2.hours) %>
<%= f.time_select :start_time, :value => "14:30" %>
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) %>
This always produces a time selector with the current time rather than the value for @invoice.start_time.
@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 %>
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" %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
@invoice.start_time 是否已分配值?我想不是。
如果您使用该代码,@invoice.start_time 将返回 nil.. 因此 :value 将始终默认为 Time.now。这里的问题是您正在使用的条件语句。我假设当您尝试创建新数据时会发生这种情况。当您填写表单时,@invoice.start_time 未填写任何值。因此,在您保存之前,它始终为零。
我建议您将代码更改为:
<%= f.time_select :start_time, :value => @invoice.start_time,:默认=> Time.now %>
实际上,如果您可以在问题中更清楚地了解您希望 time_select 助手做什么,那么事情就会变得更容易。
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 %>
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.
实际上,您可以在启动模型时尝试在控制器级别设置 start_time,例如
在控制器中:
在操作中:
您会看到表单中的 start_time 被神奇地设置了!希望这有帮助 =)
You can actually try to set start_time at the controller level when you initiate the model, e.g.
in the controller:
in the action:
And you'll see that the start_time in the form is magically set! Hope this helps =)
对我有用的是请
注意,我将其称为标签,而不是以通常的 form_for 方式。
What worked for me was
Notice that I called it as a tag and not in the usual form_for way.
它在 Rails 文档 中列出,
我自己使用过它它起作用了。
It's listed in the rails documentation
Used it myself and it worked.