Explain Codes LogoExplain Codes Logo

Rails: Get next / previous record

ruby
rails-associations
record-navigation
database-optimization
Nikita BarsukovbyNikita Barsukov·Dec 11, 2024
TLDR

To find the next or previous records based of the id:

Next:

# Call your magic carpet ride to the next record! next_record = Model.where('id > ?', current_record.id).order(:id).first

Previous:

# I prefer time travel, let's go back to the previous record previous_record = Model.where('id < ?', current_record.id).order(id: :desc).first

Just replace Model with your actual model class, and replace current_record.id with your current record's id.

Use the power of Rails associations to navigate your records. Let's say you have a User with a bunch of Photos. Here's how you can get to the next and previous photos by a user:

class Photo < ApplicationRecord belongs_to :user # Moving on up to the East Side, to a deluxe photo in the sky! def next user.photos.where("id > ?", id).order(:id).first end # Step back, you're dancing kinda close! Back to the previous photo. def previous user.photos.where("id < ?", id).order(id: :desc).first end end

This uses the has_many and belongs_to associations for contextual and efficient record navigation.

If records are organized by timestamps instead of IDs, use timestamp field like created_at:

# We're moving forward in time, like a Time Lord! def next_by_created_at user.photos.where("created_at > ?", created_at).order(:created_at).first end # And now we're stepping back in time, Marty McFly style! def previous_by_created_at user.photos.where("created_at < ?", created_at).order(created_at: :desc).first end

Augmenting record navigation

Consider the user experience and application requirements, and you can enhance single record navigation.

Containing edge cases

Always think about the first and last record. Handle gracefully such cases where there's no next or previous record.

Abstracting methods

Keep it clean and classy! Abstract the logic either within the model or a concern, enriching your code base and ease of maintenance.

Result ordering

Remember the power of ordering! It ensures consistent results, especially crucial when dealing with duplicated created_at timestamps.

Reducing database load

Save the memory! Rather than loading all the associated records, optimize database load by using limit and first.

Advanced next/previous navigation

Embrace these additional techniques to tailor your record navigation.

Add more complex conditions, or scopes, where record navigation has to satisfy certain conditions such as ownership, status, or visibility.

Pagination

Integrate pagination tools like kaminari or will_paginate for record series, improving navigation and performance simultaneously.

Personalized navigation

Consider the context. Users should navigate through records relevant to their interaction within the application.