Rails和RABL按照它所属的另一个模型对子进行排序

时间:2013-05-16 21:50:19

标签: ruby-on-rails rabl

我有3个型号:

class City < ActiveRecord::Base
  has_many :buildings
end
class Company < ActiveRecord::Base
  has_many :buildings
end
class Building < ActiveRecord::Base
  belongs_to :city
  belongs_to :company
end

我需要在每个城市展示建筑物,但按照他们的公司排序:

city1
  company1
    building1
    building2
  company2
    building3
city2
  company1
    building5
    building6
    building4
  company2
    building7
    building8

我无法弄清楚如何进行查询,或者如何正确使用rabl来生成此输出结构

修改

这就是我现在想出来的:

cities_controlles.rb:

def index
  @cities = City.all
  @companies = Company.includes(:buildings)
end

index.json.rabl:

collection @cities
attributes :id, :name
node :companies do |city|
  @companies.map do |company|
    { id: company.id, name: company.name, buildings:
     company.buildings.map do |building|
       if building.city_id == city.id
         { id: building.id, name: building.name }
       end
     end.compact
   }
  end
end

1 个答案:

答案 0 :(得分:-1)

根据应如何使用rezult,有很多方法可以做到这一点。

第一种方式:

SELECT 
    cities.name, companies.name, buildings.name
FROM
    cities
LEFT JOIN
   companies ON companies.city_id = city.id
LEFT JOIN 
    buildings ON buildings.city_id = city.id
ORDER BY
    cities.name, companies.name, buildings.name

Rezult应该像那样:

city1 | company1 | building1
city1 | company1 | building2
city1 | company2 | building3
city2 | company1 | building4
city2 | company1 | building5
city2 | company1 | building6
city2 | company2 | building7
city2 | company2 | building7

你可以用那张桌子做任何你想做的事。

第二种方式(使用汇总功能获取城市和公司的建筑物清单):

SELECT 
    cities.name, companies.name, GROUP_CONCAT(buildings.name)
FROM
    cities
LEFT JOIN
   companies ON companies.city_id = city.id
LEFT JOIN 
    buildings ON buildings.city_id = city.id
ORDER BY
    cities.name, companies.name
GROUP BY
    cities.name, companies.name

这样Rezult应该像那样:

city1 | company1 | building1, building2
city1 | company2 | building3
city2 | company1 | building4, building5, building6
city2 | company2 | building7, building8

注意聚合函数的名称(GROUP_CONCAT - 对于MySQL)在DBMS中有所不同。例如,在firebird中,它是“LIST”