Created
December 12, 2009 18:33
-
-
Save pacoguzman/255002 to your computer and use it in GitHub Desktop.
Using preload associations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Comment < ActiveRecord::Base | |
def self.preload_graffities_associations(graffities) | |
# We want to load the following data | |
# associations = [{:user => :profile}, {:replys => {:user => :profile}}] | |
# We join graffities and replys to load its users and profile to avoid two querys | |
graffities_and_replys = (graffities + graffities.map(&:replys)).flatten | |
Comment.send(:preload_associations, graffities_and_replys, {:user => :profile}) | |
end | |
end | |
graffities = profile.graffities | |
Comment Load (15.9ms) SELECT * FROM `comments` WHERE (`comments`.commentable_id = 3 AND `comments`.commentable_type = 'Profile' AND (parent_id IS NULL)) LIMIT 1 | |
Comment Load (14.5ms) SELECT * FROM `comments` WHERE (`comments`.parent_id = 2) ORDER BY created_at DESC | |
+----+----------------+------------------+-------+---------------------+---------+---------+-----------+-----+-----+-------------------------+-------------------------+ | |
| id | commentable_id | commentable_type | title | body | subject | user_id | parent_id | lft | rgt | created_at | updated_at | | |
+----+----------------+------------------+-------+---------------------+---------+---------+-----------+-----+-----+-------------------------+-------------------------+ | |
| 4 | 3 | Profile | | Esto es un graffity | | 1 | 2 | 2 | 7 | 2009-12-12 17:35:54 UTC | 2009-12-12 17:35:54 UTC | | |
+----+----------------+------------------+-------+---------------------+---------+---------+-----------+-----+-----+-------------------------+-------------------------+ | |
Comment.preload_graffities_associations(graffities) | |
Comment Load (0.5ms) SELECT * FROM `comments` WHERE (`comments`.parent_id = 4) ORDER BY created_at ASC | |
User Load (0.1ms) SELECT * FROM `users` WHERE (`users`.`id` IN (1,3)) | |
Profile Load (0.1ms) SELECT `profiles`.* FROM `profiles` WHERE (`profiles`.user_id IN (1,3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment