2017-01-31 68 views
1

有一張表可以根據餐廳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查詢以避免使前端代碼複雜嗎?關於如何做到這一點的任何想法?

+0

所以,你想改變數組進行排序的方式,對不對? – Bustikiller

+0

是@Bustikiller。所以,我們有當天的參賽名單,其次是其他日子。它會每天自動更改。 –

+0

一些思考:http://rextester.com/UTX11602 – Strawberry

回答

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) 
+0

聞聽此事:NoMethodError(未定義的方法'天」爲#<的ActiveRecord ::關係:: ActiveRecord_Relation_Restauranttiming:0x000000042b8f78>): –

+0

@SatishSaini,固定 – Ilya

+0

@Ilya確, 謝謝! – mudasobwa

相關問題