Skip to content

Instantly share code, notes, and snippets.

@Papillard
Last active December 19, 2015 21:38
Show Gist options
  • Select an option

  • Save Papillard/6021069 to your computer and use it in GitHub Desktop.

Select an option

Save Papillard/6021069 to your computer and use it in GitHub Desktop.
Query optimization !
# Initial: No counter_cach for tweet's favorites, doing a_tweet.favorites.size pulls all favorite records..
class Favorite < ActiveRecord::Base
belongs_to :tweet
end
# Final: Setting a counter_cache to keeptrack of favorites count
class AddCounterCacheColumnToTweets < ActiveRecord::Migration
def self.up
add_column :tweets,
:favorites_count,
:integer,
:default => 0
end
def self.down
remove_column :tweets, :favorites_count
end
end
class Favorite < ActiveRecord::Base
belongs_to :tweet,
:counter_cache => :favorites_count
end
# => a_tweet.favorites.size
# USE SIZE !!! not length or count
# Use find_each : not to load all records once (especially with big DB)
Tweet.find_each( :batch_size => 5 ) do |tweet|
puts tweet.status
end
# Adding index that will optimize current_user.followings.order('created_at desc')
class AddIndexesToFollowings < ActiveRecord::Migration
def self.up
add_index :followings, [:user_id, :created_at]
end
def self.down
remove_index :followings, [:user_id, :created_at]
end
end
# => ALWAYS INDEX FOREIGN KEY
# Initial
# N+1 query : 1. getting the tweet's favorites array
# 2. for N favorites, get the associated user
class Tweet < ActiveRecord::Base
has_many :favorites
def favorited_users
self.favorites.collect {|fav| fav.user }
end
end
# Initial
# 2 queries : 1. getting the tweet's favorites array including their users' id
# 2. getting the users corresponding to thes id array (1 query)
class Tweet < ActiveRecord::Base
has_many :favorites
def favorited_users
self.favorites.includes(:user).collect {|fav| fav.user }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment