我有 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 来生成这个输出结构
编辑:
这是我暂时想到的:
city_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