ericraio
ericraio

Reputation: 1469

Finding the next record in the database with Active Record

So I have my rails application and I have blog posts in my application. For starters I am on rails 2.3.5 and Ruby 1.8.7

For the show page, I am required to give a prev/next link to the prev/next blog post.

The catch is that I need to find the next blog where the language column in the database is equal to 'eng'. I had started writing this out in my model and it works but of course this will just find the prev/next record in the database no matter what the language is specified in the column and it will break when the record is not found.

def next(lang='eng')
 BlogEntry.find(self.id - 1)
end

def prev(lang='eng')
 BlogEntry.find(self.id + 1)
end

Upvotes: 2

Views: 1559

Answers (2)

David Nguyen
David Nguyen

Reputation: 331

It's generally dangerous to do id math like this because you can't guarantee that it exists. For instance, suppose you have records with id 1, 2 and 3, then you delete record 3 but create a new record, ActiveRecord will assign that to is 4 (even though 3 is not a record anymore. So if you were to do a find(self.id + 1) on record 2, you will receive an error.

The easiest way to do this is probably with a 'where' statement.

def next(lang='eng')
    BlogEntry.where(:lang => lang).where("id > ?", self.id).first
end

and

def prev(lang='eng')
    BlogEntry.where(:lang => lang).where("id < ?", self.id).last
end

I'm not familiar with the syntax of Rails version you are using, but it's probably very similar if not the same.

Upvotes: 1

Frexuz
Frexuz

Reputation: 4933

Try this. This won't break missing records.

BlogEntry.find(:first, :conditions => ["id > ? AND lang = ?", self.id, lang])

and

BlogEntry.find(:first, :conditions => ["id < ? AND lang = ?", self.id, lang])

Upvotes: 4

Related Questions