Fixing Slow Rails Lists with Active Record
Measure the page before changing it
A post list can look simple while executing a query for every author and every set of tags. Inspect development SQL logs with a realistic number of records. Record the number of queries and response time before optimizing so you can tell whether the change helped.
Load the associations the view uses
@posts = Post.where(status: :published, verified: true)
.includes(:user, :tags)
.order(created_at: :desc, id: :desc)
.limit(20)
The view can now read post.user.name and iterate post.tags without repeatedly fetching those associations. Avoid calling post.tags.pluck(:name) inside that loop: it can issue fresh SQL even when the association was loaded. Use post.tags.map(&:name) for the loaded records.
Choose indexes from the actual query
Use explain to inspect the query plan. A candidate index for this list covers status, verified, created_at, and id, but check selectivity and the database plan before adding it. Indexes consume space and add work to writes; indexing every column is not a performance strategy.
Bound the work
Use pagination rather than rendering the entire table. For large feeds, cursor pagination over created_at and id avoids increasingly expensive offsets and gives tied timestamps a stable order. Use find_each for background batch processing when display order is not required.
Verify the improvement
Compare logs and timings again with the same dataset. Check that query count stays roughly constant when the page grows from five to twenty posts. Also confirm that approval filters still apply: returning fewer queries is only useful if the page returns the correct records.
Reference: Active Record Query Interface.
Long
Reactions
Comments
Sign in to join the conversation.