我希望能够输出如下内容:
Name Car Type 1 Car Type 2 Car Type 3
Dave 1 3 6
Mike 5 2 8
关于通过积极记录实现这一目标的任何建议? (rails 3.1)
型号:
class Person
#name
has_many :sales
end
class Sales
belongs_to :person
belongs_to :car
end
class Cars
#type, id, name
has_many :sales
end
答案 0 :(得分:1)
无SQL解决方案:
sales = Sale.includes( :person, :car ).all # or whatever you want to filter
sales_by_person = sales.group_by( :person )
grouped_sales = {}
sales_by_person.each do |person,sales|
grouped_sales[person] = sales.group_by(:car).map { |car,car_sales| [ car, car_sales.size ] }
end
puts grouped_sales.inspect