Posts

Showing posts with the label rails-activerecord

Rails ActiveRecord include non-related tables into query

Rails ActiveRecord include non-related tables into query I have model Benchmark . It has method scores which is doing some calculations. During this calculations, it uses all values from table Synonyms . It has the corresponding model, but these models ( Benchmark and Synonym ) are not related to each other. I always need all synonyms in any of my benchmark calculation. Synonyms are used to replace values in a couple of strings which are Benchmark attributes. To get the synonyms I simply use the Synonym.all method inside my scores method: Benchmark scores Synonyms Benchmark Synonym Synonym.all scores def scores @synonyms ||= Hash[Synonym.all.map {|synonym| [synonym.synonym, synonym.word]}] @scores ||= # replacing substrings in Benchmark name using synonyms end So far so good. But now I want to perform bulk calculations for all the benchmarks I have. This obviously leads to N+1 query problem — each scores method calls Synonym.all method. Rails is smart enough to cache...