Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next element in array of active record objects

Ruby on Rails Next/Previous Post

I have an index page - posts#index which has links to the show pages of each post. Each post references a particular topic and may have been created at different times, so the id's of the posts aren't necessarily sequential for all the posts in that topic. I want to be able to go to the next & previous posts for a particular topic.

In my PostsController I've got instance variables for all the posts for a topic and the particular topic being shown

def index
  @topic = Topic.find(params[:topic_id])
  @posts = @topic.posts.all
end

def show
  @topic = Topic.find(params[:topic_id])
  @posts = @topic.posts.all
  @post = @topic.posts.find(params[:id])
end

@posts is an array of active record objects @posts => #<ActiveRecord::AssociationRelation [ #<Post id: 73, topic_id: 3>, #<Post id: 74, topic_id: 3>, #<Post id: 76, topic_id: 3>, #<Post id: 77, topic_id: 3>, #<Post id: 91, topic_id: 3>]

If this was an array of ruby objects I could use @posts.index(@post) to find the id of a particular element of the array and then do either index + 1 or index - 1 to traverse the array of posts, but .index is a different method in active record. If I'm on the show page for any given post in a particular topic, Post id: 76 for example, how can I go to link_to Post id: 74 (next) and link_to Post id: 77 (previous) in a way that work for any post in a particular topic?

like image 662
Tyler Crosse Avatar asked Feb 02 '26 12:02

Tyler Crosse


1 Answers

You can simply do the following:

def show
  @topic = Topic.find(params[:topic_id])
  posts = @topic.posts.order('posts.id ASC')
  @post = posts.find(params[:id])
  @previous_post = posts.where('posts.id < ?', @post.id).first
  @next_post = posts.where('posts.id > ?', @post.id).first
end
like image 189
MrYoshiji Avatar answered Feb 04 '26 02:02

MrYoshiji