我想創建一個基於我的數據庫結構的JSON數組(字符串實際)。我有以下關係:從ActiveRecord創建JSON文件,並避免N + 1
Country > State > City
我現在做它的方式是非常innefficient(N + 1):
data = "[" + Country.all.map{ |country|
{
name: country.name,
states: country.states_data
}.to_json
}.join(",") + "]"
然後在國家型號:
def states_data
ret_states = []
states.all.each do |state|
ret_states.push name: state.name, cities: state.cities_data
end
ret_states
end
然後在州模型上:
def cities_data
ret_cities = []
cities.all.each do |city|
ret_cities.push name: city.name, population: city.population
end
ret_cities
end
如何我可以更有效地做到這一點嗎?
它只對狀態做「IN(...)」,城市每個狀態仍然被查詢一次:( – Manuel