Keenan Thompson
Keenan Thompson

Reputation: 980

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.

Upvotes: 5

Views: 2068

Answers (1)

mkk
mkk

Reputation: 7693

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

Upvotes: 12

Related Questions