making a 'next' link, but (id+1) record might not exist in the database
so i want to make a page the displays a Phrase
by select (initially) at random from the database. on that page i want a <%= link_to "next"%>
but i was wondering if there was an efficient way to ensure that the next record exists
currently I'm using just
# @phrase is current phrase
<%= link_to "next", phrase_path( Phrase.find( @phrase.id + 1 ) ) %>
yes, i know i should call a @next from the controller, or better yet have a next method in the model to call @phrase.next, but this is for illustra开发者_如何学运维tive purposes.
but this often turns up an ActiveRecord::RecordNotFound
error because some phrases have been deleted from the db (due to moderation, error, etc...). I could rescue from this and loop that till it works in the controller then pass it or something, but that seems like a bad solution, and not particularly 'railsy'
is there a convenient solution to this anyone has found
figured it out
based on this link which is a little outdated, uses named_scope
from back in rails 2. I first rewrote it using the new rails 3 scope
style, but then just changed it to a method. just used
def next
Phrase.where("id > ?", self.id).order("id ASC").first
end
def previous
Phrase.where("id < ?", self.id).order("id DESC").first
end
Try creating a next/previous scope on your model, as suggested in http://steve.dynedge.co.uk/2010/01/13/random-previous-and-next-entries-from-active-record-models-using-offset/
This will allow you to do something like:
Phrase.next(5) or Phrase.next(@phrase.id)
Why don't you create a method in the controller called next and pass in the current record id. It would be trivial from there to redirect the user back to the show page for that next resource.
If you are deadset on creating the link in advance, look into creating a helper method to find the next record that exists and make it available in your views. Then you could call that whenever you needed the id of the next available record.
Something like will_paginate might be of help too. I know your page size is just one, but the essence of what you're doing is pagination.
精彩评论