0

Using Mongoid / MongoDB, how can I find a document whose name in either available language match my where query ?

Assume I have a model with a localized field and many translations

class Foo
   field :name, localize: true
end

Foo.create(name_translations: { 
  'fr' => 'Ingénierie logicielle',
  'en' => 'Computer Software'
})

The .find_by(name: ) method only seems to find the I18n.current language (French in my case), how can I search across all translations ?

I'm trying several of variations of Foo.find_by(name_translations: 'Computer Software), but I'm still getting empty results...

Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

1

Maybe there's a more elegant solution, but since it appears that name is an embedded document, you'll need to match against each language:

term = 'Computer Software'
Foo.or({ :'name.en' => term }, { :'name.fr' => term })
mikwat
  • 533
  • 3
  • 11
  • Hey, just realized the name of the field in MongoDB was actually `name` and `name_translations` came from mongoid. Therefore I can get away with just `Foo.or( { :'name.en' => term } , { :'name.fr' => term })` if you wish to update your solution. I guess I can build this query by iterating on I18n.available_languages – Cyril Duchon-Doris Apr 25 '18 at 07:44