Reputation: 85
I implemented a prev/next post method in my blog rails application but the previous method is giving errors. Not sure what to
# app/models/post.rb
def next
Post.where("id > ?", id).limit(1).first
end
def prev
Post.where("id < ?", id).limit(1).first
end
Then in my view:
# app/views/posts/show.html.erb
<%= link_to "Prev Post", @post.prev %>
<%= link_to "Next Post", @post.next %>
"Next" works perfectly, but "prev" seems to link to the very first post written instead of the one before it. What am I doing wrong?
Upvotes: 1
Views: 28
Reputation: 14784
Try using .last
def prev
Post.where("id < ?", id).limit(1).last
end
Upvotes: 0
Reputation: 230481
It's because you didn't specify sort order. I wouldn't be suprised if next
also didn't work (sometimes). When you rely on order of things, specify it explicitly.
def next
Post.where("id > ?", id).order(id: :asc).limit(1).first
end
def prev
Post.where("id < ?", id).order(id: :desc).limit(1).first
end
Upvotes: 1