2014-11-25 3 views
0
class BillableEvent < ActiveRecord::Base 
    has_many :billable_jobs 
end 

class BillableJob < ActiveRecord::Base 
    belongs_to :billable_event 
    belongs_to :job 
end 

class Job < ActiveRecord::Base 
    has_many :billable_jobs 
    belongs_to :customer 
    acts_as_list scope: :customer_id 
    default_scope {order(:position)} 
end 

class Customer < ActiveRecord::Base 
    has_many :jobs 
end 

class BillableEventController < ApplicationController 
    def invoice 
    @billable_jobs = @billable_event.billable_jobs 
    @jobs = # ... what should I put here? 
    end 
end 

나는보고 싶습니다 예를 들어레일에 중첩 속성을 그룹화하고 정렬하려면 어떻게합니까? 내보기에서

%table.invoice 
    - @jobs.each do |job, billable_jobs| 
    %tbody 
     %tr.title 
     %td.title{colspan: '4'}= job.stand_alone_title 
     - billable_jobs.each do |billable_job| 
     = content_tag_for(:tr, billable_job) do 
      %td &nbsp; 
      %td= billable_job.user.name 
      %td= billable_job.billable_price 
      %td= button_to 'Invoice' 

: 작업이 그룹화 및 고객 제목으로 분류되어 있습니다

Amber - Job 1 
    A-BillableJob $10 
    B-BillableJob $25 
Amber - Job 2 
    A-BillableJob $10 
Paul 
    A-BillableJob $25 
    B-BillableJob $10 

. 위의 이름은 고객 제목에서 파생 된 작업 stand_alone_title의 예입니다. 고객이 작업을 그룹화하는 모든 방법은 해시 또는 정렬로 변환하여 올바르게 정렬 할 수없는 것으로 보입니다.

답변

1

group_by를 수행하면 array로 변환되지만 Array 클래스에있는 sort_by 메소드로 배열을 정렬 할 수 있습니다.

class BillableEventController < ApplicationController 
    def invoice 
    @billable_jobs = @billable_event.billable_jobs 
    # group records by customer 
    customers = @billable_jobs.group_by{|e| e.job.customer} 
    # when you call group_by it creates array 
    # [<customer> => [<billable_j1>, <billable_j2>, ..], <customer_2> => [<billable_j>, ...]] 
    @customers = jobs.sort_by{|customer, jobs| customer.title} 
    # method sort_by from Array class sorts array 
    # and takes argument to sort by 
    end 
end 
+0

해결책은 저에게 있습니다. 나는 내가 그것을 어떻게 가져 갔는지 보여주는 당신의 대답을 편집했다. 감사. – Preacher

관련 문제