How do I add an index and override an existing attribute?
I am getting the entry by code just like these
@community = Community.find_by_community_name(params[:community_name])
@user = User.find_by_username(params[:username])
I want to speed up loading, so I'm going to add an index to them that way. If I do rake db:migrate
, is it reindexed into existing records as well?
Or just records to be created from now on?
Does adding an index improve loading speed the same way?
class AddIndexToCommunity < ActiveRecord::Migration
def self.up
add_index :communities, [:community_name, :title, :body], :name=>:communities_idx
end
def self.down
remove_index :communities, [:community_name, :title, :body], :name=>:communities_idx
end
end
class AddIndexToUser < ActiveRecord::Migration
def self.up
add_index :users, [:username, :nickname, :body], :name=>:users_idx
end
def self.down
remove_index :users, [:username, :nickname, :body], :name=>:users_idx
end
end
source to share
rake db:migrate
will migrate the database and apply the indexes immediately. You should only apply indexes to the columns you are using in your searches. Remember that in insert
and mode update
penalty points are imposed. If you're loading records by your own names
, add indexes only to names
:
class AddIndexToCommunity < ActiveRecord::Migration
def self.up
add_index :communities, :community_name
end
def self.down
remove_index :communities, :community_name
end
end
class AddIndexToUser < ActiveRecord::Migration
def self.up
add_index :users, :username
end
def self.down
remove_index :users, :username
end
end
source to share