我正在尝试根据我的数据库结构创建一个 json 数组(实际上是字符串)。我有以下关系:
Country > State > City
我现在这样做的方式非常低效(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
我怎样才能更有效地做到这一点?