【问题标题】:Get an array of many objects associations获取多个对象关联的数组
【发布时间】:2019-07-25 05:41:06
【问题描述】:

我不知道如何找到一个可以理解的标题,所以我会尽力解释我的问题。

我有 2 个模型: - 可通过全球化翻译的国家/地区,具有名称和许多地区 - 地区所属国家/地区

我想做的是让所有地区的数组形成一个国家数组。

例如

Country.all.regions
Country.with_translations(I18n.locale).order("country_translations.name asc").regions

有一个简单的方法来获取这个数组吗?

【问题讨论】:

  • Country.all.map {|country| country.regions }.flatten
  • 谢谢它正是我想要的。我为别人回答了你的答案!

标签: ruby-on-rails ruby has-many globalize3 globalize


【解决方案1】:

@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
  • 清理它的另一件事是:Country.includes(:regions).all.flat_map(&:regions)
【解决方案2】:

来自@Octopus-Paul:

Country.all.map {|country| country.regions }.flatten

【讨论】:

    【解决方案3】:

    只需搜索与您的国家列表相匹配的地区:

    countries = Country.all
    regions = Region.where(country: countries)
    

    【讨论】:

    • 我知道这很明确,但尝试添加更多文字来解释为什么您的解决方案是好的解决方案
    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 2019-12-03
    相关资源
    最近更新 更多