在顶部显示当前日期的值,然后显示其他日期

时间:2017-01-31 07:39:48

标签: mysql ruby-on-rails ruby erb

我可以根据餐厅ID从表格中获取行列表。例如,

SELECT id, start_time, end_time, day FROM restaurant_timings WHERE restaurant_id = 2

输出看起来像

1 6:00am 7:00pm Sunday
2 6:00am 5:00pm Monday
3 6:00am 4:00pm Tuesday
4 6:00am 7:00pm Wednesday
5 6:00am 9:00pm Thursday
6 6:00am 6:00pm Friday
7 6:00am 7:00pm Saturday

这些结果以数组@timings的形式返回。现在,在前端我希望根据当天显示这些结果。话虽如此,如果今天星期三那么我需要在顶部显示星期三,然后在其他所有日期显示。我正在使用循环来执行此操作。这是循环代码:

<% @timings.each do |val| %>
<tr>
   <td><%= val['day_name'] %></td>
   <td>
      <div class="form-group">
         <div class='input-group date datetimepicker1' id='datetimepicker1'>
            <input type='text' class="form-control editabletext" name="openingtime[]" value="<%= if val['opening_time'].present? then val['opening_time'].strftime("%m/%d/%Y %I:%M %p") end %>" readonly/>
            <span class="input-group-addon"><span class="glyphicon glyphicon-calendar icon-calendar"></span>
            </span>
         </div>
      </div>
   </td>
</tr>
<% end %>

应该/我可以修改SQL查询以免使前端代码变得复杂吗?关于我该如何做的任何想法?

1 个答案:

答案 0 :(得分:2)

在这种特殊情况下修改后端代码更容易:

@timings = ActiveRecord::Base.connection.execute %|
  SELECT id, start_time, end_time, day
  FROM restaurant_timings
  WHERE restaurant_id = 2|

until Date.today.public_send("#{@timings.first.day.downcase}?") do
  @timings.rotate!
end

或者,甚至更好:

@timings.rotate!(Date.parse(@timings.first.day).wday - Date.today.wday)