Reputation: 1321
I have a Toy and ToyPart ActiveRecord classes. Toy has_may ToyPart relationship. The ToyPart ActiveRecord has a content field where the ToyPart is described and a type_desc field where very briefly describes ToyPart.
I need to get all Toy records based on content and type_desc fields from ToyPart. I did this statement to get th results:
Toy.all.to_a.toy_parts do {|toy_part| toy_part.where("content like (?) and type_desc='arm'", "%Left arm from%" }
This query takes too much time to return results. Toy table has more than 270000 records and each Toy has at least 5 ToyPart results.
I'm new to Ruby and on Rails. transform all record to an array I believe it's a huge process and doing another query in a loop the costs increases even more.
to_a is not a good idea. To alleviate processing what can I do to improve that?
P.S: I'm using rails 4.2.6.
Upvotes: 0
Views: 41
Reputation: 2747
Have you tried using joins
? Something like this:
Toy.joins(:toy_parts).where("toy_parts.content like (?) AND toy_parts.type_desc='arm'", "%Left arm from%"")
Upvotes: 3