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 this query and avoid tons of DB queries but I'm still wondering is there some way to tell ActiveRecord that all my Benchmarks always include all Synonyms? I can't use belongs_to/has_many/etc because my tables are not linked.
scores
Synonym.all
One of the solutions I've used in the similar case was to fetch Synonym.all
, then fetch Benchmark.includes(:...).all
, and then inject synonyms manually into each benchmark, like benchmarks.each {|b| b.synonyms = @synonyms}
but I'm looking for more elegant approach.
Synonym.all
Benchmark.includes(:...).all
benchmarks.each {|b| b.synonyms = @synonyms}
I use Rails 5.
Calculations are a bit complex and I believe they're not related to questions, but synonyms are used to replace some values in string which is loaded along with benchmark. I'll add this clarification into question.
– Vladimir Rozhkov
Jun 29 at 10:46
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
"doing some calculations using synonyms" - can you show what they are?
– Jagdeep Singh
Jun 29 at 10:41