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
%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
的示例,它来自客户标题。)我知道按客户对作业进行分组的每种方式都将其转换为我似乎无法排序的哈希或数组正常。
答案 0 :(得分:2)
您可以执行group_by并将其转换为数组,但您可以使用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