作者:Mr_小迪2502897623 | 来源:互联网 | 2023-05-24 19:17
我不知道如何找到一个可以理解的标题,所以我会尽力解释我的问题.
我有2个模型: - 可全球化的国家,名称和许多地区 - 地区所属国家
我想做的是从一系列国家/地区制作一系列所有地区.
例如
Country.all.regions
Country.with_translations(I18n.locale).order("country_translations.name asc").regions
有一个简单的方法来获得这个数组?
1> Rodrigo..:
@ Octopus-Paul解决方案有效,但它有n + 1个查询问题.要避免它,请使用该includes
方法.
Country.includes(:regions).all.map {|country| country.regions }.flatten
在这里阅读更多内容:http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
你可以做的一个很好的技巧是使用`.flat_map {...}`而不是`.map {...} .flatten`.