如何在连接表上执行where where where而不在循环中查询db

时间:2017-06-25 11:19:34

标签: ruby-on-rails activerecord

我有以下型号

App has_many features
Feature has_many translations

现在我想查找翻译,看看是否需要创建或更新。

    App.joins(features: :translations).first.features.each do |feature|
      languages.each do |lang|
        translation = feature.translations.where(language: lang).first_or_initialize
    end
   end

现在问题是我对每种语言都有一个数据库查找,这是一个很大的问题,因为我有很多功能。 如何在加入表中查找翻译时,如何从预先加载中受益?

1 个答案:

答案 0 :(得分:1)

让我们将语言分成两个数组:found和not_found:

 found, not_found = languages.partition do |lang| 
   App.joins(:features => :translations).where("translations.language" => lang).present?
 end

 found_language_translations = Translation.where("language in (?)", found)
 new_language_translations = not_found.map{|lang| Translation.new(language: lang) } #This will fire up too many queries though :/