How do I set a time in a time_select view helper?

2019-08-04 10:22发布

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" %>

4条回答
迷人小祖宗
2楼-- · 2019-08-04 11:01

What worked for me was

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

Notice that I called it as a tag and not in the usual form_for way.

查看更多
闹够了就滚
3楼-- · 2019-08-04 11:14

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.

查看更多
Animai°情兽
4楼-- · 2019-08-04 11:15
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'})

It's listed in the rails documentation

Used it myself and it worked.

查看更多
仙女界的扛把子
5楼-- · 2019-08-04 11:16

You can actually try to set start_time at the controller level when you initiate the model, e.g.

in the controller:

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

in the action:

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

And you'll see that the start_time in the form is magically set! Hope this helps =)

查看更多
登录 后发表回答