Question

Say I have simply ran rails g scaffold book name:string about:text On the 'show' view, how would I implement a button to go to the next item in the model.

I can't simply do @next = @book.id + 1 because if @book.id = 2 (for example) and I clicked destroy on the book with an id of 3. It would result in a broken page.

Was it helpful?

Solution

You can do:

 @next = Book.first(:conditions => ['id > ?', @book.id], :order => 'id ASC')

Remember to check whever @next is not nil

To be even cooler, you can create a method in your model like so:

def next
  Book.first(:conditions => ['id > ?', self.id], :order => 'id ASC')
end

then if you have @book you should be able to invoke it like

@book.next

haven't written anything in RoR recently but this looks reasonable to me;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top