Select specific fields for performance:
database schema fo user model:
class User.rb
#fields
field :email, type: String, default: ""
field :encrypted_password, type: String, default: ""
field :first_name, type: String
field :last_name, type: String
field :age, type: Integer
field :sign_in_count, type: Integer, default: 0
field :current_sign_in_at, type: Time
field :last_sign_in_at, type: Time
field :current_sign_in_ip, type: String
field :last_sign_in_ip, type: String
field :provider, type: String
field :uid, type: String
field :description, type: String
end
The users index page displays 10 posts. At the beginning, I used
class UsersController < ApplicationController
def index
@posts = User.paginate(:page => params[:page])
end
end
sql query:
SELECT * FROM users LIMIT 0, 10
It was very slow when the user has huge description.
In rails there is a method "select" to fetch specific fields, Here I give you the way.
class User
INDEX_COLUMNS = column_names - ['description', 'encrypted_password', sign_in_count', 'current_sign_in_at', 'last_sign_in_at', 'current_sign_in_ip', 'last_sign_in_ip']
end
class PostsController < ApplicationController
def index
@posts = Post.select(Post::INDEX_COLUMNS).paginate(:page => params[:page])
end
end
Here rails tells database fetch only name, email, age, uid
SELECT name, email, age, uid, description FROM `posts` LIMIT 0, 10
It is faster than before and use less memory.
NOTE:
You should not select specific fields if you use memory object caching system, such as memcache.