Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Get next item in model

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.

like image 987
Keenan Thompson Avatar asked Aug 26 '11 19:08

Keenan Thompson


1 Answers

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;)

like image 81
mkk Avatar answered Nov 04 '22 02:11

mkk