Speed up your ActiveRecord queries with Model.select
Say you want to display a list of all your users' names and link to their show pages. Instead of runningUser.all
, instantiating every field of every user, there's a better way. Since you only need the name and id or slug (for the link), better to run: @users = User.select(:name, :email)
That will instantiate user objects with just those attributes, saving memory and database query time.
Also, brand new for Rails 4.2, you can presumably print out the fields selected by called
@users.first.accessed_fields
. This is primarily helpful in development mode so you know which fields you have access to. However, I couldn't get this to work locally, might need to be using master branch of Rails. Read more here: https://github.com/rails/rails/commit/be9b680