2010-04-19 74 views
1

我有一個time_select,我試圖設置一個時間值如下;如何在time_select視圖助手中設置時間?

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

這總是會生成一個帶有當前時間的時間選擇符,而不是@ invoice.start_time的值。

@ invoice.start_time事實上是一個DateTime對象,但這被傳遞給時間選擇就好了,如果我使用

<%= f.time_select :start_time %> 

我想我真的問的是如何使用:價值選擇用time_select幫手。像下面這樣的嘗試似乎沒有產生期望的結果;

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

回答

5

Has @ invoice.start_time是否賦值給它?我猜不會。 @ invoice.start_time將返回零如果您使用該代碼..因此:值將始終默認爲Time.now。這裏的問題是您正在使用的條件語句。我假設這是在您嘗試創建新數據時發生的。填寫表單時,@ invoice.start_time沒有填充任何值。因此它一直到你保存爲止。

我建議你的代碼更改爲:

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

其實,如果你能在你的問題,就是你希望你的time_select幫手做的話,那就讓事情變得更容易些什麼明確的。

1

您可以嘗試在啓動模型時在控制器級別設置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奇蹟般地設定!希望這有助於=)

1
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'}) 

它在用它的軌道documentation

列出自己和它的工作。

+0

提示是不同的。雖然你可能會得到相同的結果,但它應該告訴你一些類似'選擇時間'的東西。但是如果你想使用提示來指定一個選定的值,那麼相同的值將再次出現作爲其中一個選項。 – Renra 2012-06-12 14:04:40

+2

要麼只是我或者這個幫手的文檔很缺乏。 – Renra 2012-06-12 14:05:09

3

什麼工作對我來說是

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

注意,我把它叫做一個標籤,而不是在通常的form_for方法。

相關問題