我是ROR的新手,我很難做到這一點。Rails上的group_by怎麼樣
我有一個Working_hour型號和商人模型,其中商人的has_many working_hours和working_hour屬於商人,如下:
class Merchant < ApplicationRecord
has_many :working_hours, inverse_of: :merchant, dependent: :destroy
accepts_nested_attributes_for :working_hours, reject_if: :all_blank, allow_destroy: true
end
工時表
create_table "working_hours", force: :cascade do |t|
t.integer "day"
t.time "open_time"
t.time "close_time"
t.integer "merchant_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["merchant_id"], name: "index_working_hours_on_merchant_id"
end
商家可以有兩個working_hours同一天。
我的觀點:
<% @merchant.working_hours.order(:day).each do |wh| %>
<li>
<%= t(:"date.abbr_day_names")[wh.day.to_i] %> :
<%= wh.open_time.to_formatted_s(:time) %> -
<%= wh.close_time.to_formatted_s(:time) %>
</li>
<% end %>
當我在一天下令檢索到的數據的視圖中顯示爲:
Mon: 10:00-13:00
Mon: 17:00-20:00
Tue: 10:00-13:00
Tue: 17:00-21:00
Wed: 10:00-13:00
我怎麼能集團通過天working_hours和顯示是這樣的:
Mon: 10:00-13:00/17:00-20:00
Tue: 10:00-13:00/17:00-21:00
Wed: 10:00-13:00
我看了Railscast的group_by教程,但我沒有一個控制器working_hour模型。有任何想法嗎?
看起來你已經掌握了你所需要的所有數據。你只需要正確操縱它。也許從你的視角發佈代碼? – phillyslick
我編輯了我的問題。做這個Ben很簡單嗎? – user1301037