MikeHolford
MikeHolford

Reputation: 1931

Order by time_field

I have a database table called "bookings" which users can select the 'time_from' and 'time_to' in which they want the booking done.

When adding these fields to the database I added them as a time_field.

<%= f.label :time_from, "From (24hr Clock)" %>
<%= f.time_field :time_from %>

<%= f.label :time_to, "To (24hr Clock)" %>
<%= f.time_field :time_to %>

The form works and saves correctly but my problem is the order. Below is my controller code and subsequently my view to display the time and its output. Any idea on how to order these by time correctly?

Controller:

def show
    @location = Location.find(params[:id])
    @booking = Booking.order("time_to")
    @company = Company.all
end

View:

<% 0.upto(11.to_i).each do |day_count| %>
    <span class="col-md-3 booking-times">
        <h4><%= time_tag(Date.today + day_count.days) %></h4>
        <span class="label label-danger no-bookings">No Bookings</span>
        <% @booking.each do |b| %>
            <% if b.date == Date.today + day_count.days && b.type == "Meeting" %>
                <% if b.location == params[:id] %>
            <span class="label label-info booking-time">
                <%= time_tag(b.time_from, :format=>"%H:%M") %> -
                <%= time_tag(b.time_to, :format=>"%H:%M") %>
            </span>
                    <% @company.each do |c| %>
                        <% if c.id == b.company %>
                            <%=link_to c.name, c %></br>
                        <% end %>
                    <% end %>
                <% end %>
            <% end %>
        <% end %>
    </span>
<% end %>

Output: (For first day time)

09:30 - 10:30
22:00 - 23:00
07:30 - 08:30

I appreciate this is not the nicest looking code. I would like the above output to order by time. Any ideas? I have tried to order in the controller, this effects the layout but not in the correct order still. I think the dat attatched to the time_to input may be having ian affect? Thanks!

Upvotes: 0

Views: 89

Answers (2)

Dheer
Dheer

Reputation: 793

Can you please try this:

@booking = Booking.order('time_to desc')

Upvotes: 1

Richard Peck
Richard Peck

Reputation: 76784

Have you tried this:

@booking = Booking.order(time_to: :desc)

Upvotes: 1

Related Questions