Follow mekdigital on Twitter

ActiveRecord: hash_all!

During hard times where JOINS are not allowed and performance matters (i.e. don't create objects unless is really necessary), too many times I've been writing ActiveRecord find all, loop on the collection and return an hash where key is some column of the object...

Classic Scenario:

find :messages, :include :sender, :include :recipient

This will usually result in a reasonable query, but as the complexity grows things can get out of control with AR generating unnecessary db calls.

Optimized Scenario:

find :messages

find :users with ids in messages.map(&:sender_id) + messages.map(&:recipient_id)

and finally loop on messages and assign sender and recipient names as attr of the message, but this is still expensive.

Optimized Scenario V2:

find :messages

find users with hash_all on users passing once again the condition of ids being in messages.map(&:sender_id) + messages.map(&:recipient_id)

finally users[msg.sender_id] and users[msg. recipient_id] will be available at no additional cost.

 

published on 15 Dec

Comments (0)

Leave a comment...