如何在time_select视图助手中设置时间?

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

 (@invoice.start_time ? @invoice.start_time : Time.now) %> 

这总是产生一个时间选择器,其中包含当前时间而不是@ invoice.start_time的值。

@ invoice.start_time实际上是一个日期时间对象,但如果我使用的话,这会被传递给时间选择器

  

我想我真正想问的是如何将:value选项与time_select助手一起使用。 像下面这样的尝试似乎没有产生预期的结果;

  (Time.now + 2.hours) %>  "14:30" %> 

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

我建议您将代码更改为:

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

实际上,如果你在问题中能够更清楚地了解你希望你的time_select帮助者做什么,那么它会让事情变得更容易。

对我有用的是

 <%= time_select :object_name, :attribute_name, :default => {:hour => '10', :minute => '20'} %> 

请注意,我将其称为标记,而不是通常的form_for方式。

实际上,当您启动模型时,您可以尝试在控制器级别设置start_time

在控制器中:

 InvoicesController < ApplicationController # if you're creating a new object def new @invoice = Invoice.new(:start_time => Time.now) end # if you're updating an existing object def edit @invoice = Invoice.find(params[:id]) @invoice.start_time = Time.now if @invoice.start_time.nil? end end 

在行动中:

 <% form_for @invoice do |f| %> ... <%= f.time_select :start_time %> ... <% end %> 

你会看到表单中的start_time被神奇地设置了! 希望这有助于=)

 time_select(object, method, :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'}) eg.time_select(:invoice, :start_time, :prompt => {:hour => '15', :minute => '30'}) 

它列在rails 文档中

自己使用它,它工作。