Rails time select to show only hour?

4.1k views Asked by At

How do I make Rails time select to show only the hour part without the minutes? Basically what I want is to show a time filter with start_time and end_time and use Ransack gem to filter the query.

# db
create_table "schedules"
  t.time "start_time"
  t.time "end_time"

# controller
@q = Schedule.ransack(params[:q])
@q.sorts = ['date asc', 'start_time asc', 'end_time asc'] if @q.sorts.empty?
@schedules = @q.result.includes(:klass, :partner, :city)

#view
<%= search_form_for @q do |f| %>
  <%= f.label :start_time_gteq, "Start time" %>
  <%= f.select_hour :start_time_gteq, start_hour: 5, end_hour: 23 %>

  <%= f.submit "Filter" %>
<% end %>

But it gives me this error:

undefined method `select_hour' for #<Ransack::Helpers::FormBuilder:0x007fb85217e000>

I also tried:

<%= f.time_select :start_time_eq, start_hour: 5, end_hour: 23 %>

...but it shows the minute part. I checked with the API but there's no way to show only hours with the time_select.

EDIT:

Apparently there is a way to remove the minute part:

<%= f.time_select :start_time_gteq, discard_minute: true %>

Unfortunately it also generates hidden input tags that defaulted to the system's current minute, which made the filtering useless.

2

There are 2 answers

4
Topher Hunt On

Maybe it's time to just generate your own custom select rather than trying to force-fit the Rails helpers... perhaps something like this:

<%= f.label "start_hour_eq", "Start time" %>
<%= f.select "start_hour_eq", (5..23).to_a %>:00

Depending on what input Ransack expects you may need to tweak the name and/or include a hidden field for the minutes:

= hidden_field_tag "start_minute_eq", 0
0
thisismydesign On

How about: https://apidock.com/rails/ActionView/Helpers/DateHelper/select_hour

select_hour(datetime, options = {}, html_options = {}) public

Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.