Reputation: 2198
I have the following models
App has_many features
Feature has_many translations
Now I want to lookup a translation in order see to if I need to create or update.
App.joins(features: :translations).first.features.each do |feature|
languages.each do |lang|
translation = feature.translations.where(language: lang).first_or_initialize
end
end
Now the problem is that I have a db lookup for each language which is quite a problem since I have a lot of features. How can I benefit from eager loading in order to just lookup the translation in the joined table?
Upvotes: 1
Views: 34
Reputation: 624
Lets partition the languages into two two arrays, found and 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 :/
Upvotes: 1