2016-09-15 3 views
0

나는 ROR에 아주 익숙하다. 나는 이것을 달성하는 데 어려움을 겪고있다.group_by on Rails

나는 다음과 같은 Working_hour 모델 및 상인 has_many의 working_hours 및 working_hour가 가맹점에 속한 가맹점 모델, 가지고 : 상인 두 working_hours을 가질 수

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 

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 

근무 시간 테이블을 같은 날.

내보기 :

<% @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 %> 

내가 검색 한 데이터가 하루 주문한보기에 표시됩니다 : I 그룹 일에 의해 working_hours 및이 방법을 표시 할 수있는 방법

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 

:

Mon: 10:00-13:00/17:00-20:00 
Tue: 10:00-13:00/17:00-21:00 
Wed: 10:00-13:00 

레일 스케이프에서 group_by 튜토리얼을 봤지만 컨트롤러가 없습니다. working_hour 모델. 어떤 아이디어?

+0

보기에 필요한 모든 데이터가있는 것처럼 보입니다. 당신은 그걸 제대로 조작 할 필요가 있습니다. 아마도보기에서 코드를 게시 할 수 있습니까? – phillyslick

+0

내 질문을 편집했습니다. 그 벤을하는 것이 간단할까요? – user1301037

답변

1

당신은 루비 열거의 구조 당신에게 새 컬렉션을 줄 것이다 group_by

{ 
    key: matching collection items (minus item grouped on), 
    key2: matching collection items (minus item grouped on) 
} 

이 의미합니다 사용할 수 있습니다 귀하의 지금 키가 정수 중 하나가 될 해시 구조에 적용됩니다 .each 또는 당신이 그룹화 한 것,이 경우에는 정수일 수도 있고, 일치하는 subcollection이지만 grouped_by 속성을 제거한 것입니다. 따라서 귀하의 경우이 모든 그룹이 대규모 데이터 세트에 대한 문제가 발생할 것입니다 루비 층에서 수행되는 의미

<% @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 %> 

<% @merchant.working_hours.order(:day).group_by(&:day).each do |day, whs| %> 
    <%= t(:"date.abbr_day_names")[day.to_i] %> : 
    <%= whs.each_with_index do |wh, index| %> 
    <li> 
     <%= wh.open_time.to_formatted_s(:time) %> - 
     <%= wh.close_time.to_formatted_s(:time) %> 
    </li> 
    <%# if we have more than one entry add slash %> 
    <%= if index > 0 %> 
    /
    <% end %> 
    <% end %> 
<% end %> 

로 주를 다시 작성할 수 있으며, 또한 당신은 지금이야 루비 레이어에서 AREL 지연로드 기능을 잃게됩니다.정렬은 이제 "sub-collection"에 새로운 SQL 순서를 적용하는 것에 비해 루비에서 수행되어야합니다. 당신은 이상적으로 SQL 그룹을 원할 것입니다. 그러나 그것은 또 다른 시간입니다.

참고이 코드를 테스트하지 않았으므로 ... YMMV와 같이 포맷을 다시해야합니다.

+0

감사합니다. 지금 당장은 그렇게됩니다. =) 초보자가 SQL 그룹에 대해 배우려면 어떤 자료를 권장합니까? – user1301037

+0

시작 하시겠습니까? https://alexpeattie.com/blog/grouping-activerecord-by-day-or-week-with-datetrunc – user1301037

+0

대부분 google-fu 또는 현지 도서관입니다. SQL은 핵심 부분을 많이 변경하지 않았으므로 라이브러리의 대부분의 내용이 적합해야합니다. MySQL을 사용하고 속도를 원한다면, 내가 시작했을 때 이것이 권장되었습니다. http://shop.oreilly.com/product/0636920022343.do – engineerDave

1

값을 해시에 저장하고 필요한 형식으로 인쇄 할 수 있습니다. 해시에

t(:"date.abbr_day_names")[wh.day.to_i]되며

그러면 @merchant_working_hours 사용할 수 배열 단부

@merchant_working_hours = {} 
@merchant.working_hours.order(:day).each do |wh| 
@merchant_working_hours[t(:"date.abbr_day_names")[wh.day.to_i].to_s] ||= [] 
@merchant_working_hours[t(:"date.abbr_day_names")[wh.day.to_i].to_s] = wh.open_time.to_formatted_s(:time).to_s + '-' + wh.close_time.to_formatted_s(:time).to_s 

wh.open_time.to_formatted_s(:time) - wh.close_time.to_formatted_s(:time)는 것이다 해시

<% @merchant_working_hours.each do |key,value| %> 
<%= key: value%> 
<% end %> 

값을 원하는 형식으로 인쇄하면 만든 날짜를 사용하고 값 또는 개봉 시간과 종료 시간을 업데이트하여 같은 날을 확인하거나 1 주일 이상의 데이터가있는 경우에는 확인할 수 있습니다.

+0

이것은 기본적으로 루비의 group_by가하는 것입니다. – engineerDave