简体   繁体   English

使用Active Record在数据库中查找下一条记录

[英]Finding the next record in the database with Active Record

So I have my rails application and I have blog posts in my application. 所以我有我的rails应用程序,并且我的应用程序中有博客文章。 For starters I am on rails 2.3.5 and Ruby 1.8.7 首先,我处于2.3.5和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'. 问题是,我需要找到下一个博客,其中数据库中的语言列等于“ 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. 我已经开始在模型中写出它,并且可以工作,但是当然,无论该列中指定了什么语言,它都只会在数据库中找到prev / next记录,并且在找不到记录时会中断。

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

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

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

It's generally dangerous to do id math like this because you can't guarantee that it exists. 像这样进行id数学运算通常很危险,因为您不能保证它存在。 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. 例如,假设您有ID为1、2和3的记录,然后删除记录3但创建一个新记录,ActiveRecord会将其分配为4(即使3不再是记录了。因此,如果要执行在记录2上找到(self.id + 1),您将收到一个错误。

The easiest way to do this is probably with a 'where' statement. 最简单的方法可能是使用“ where”语句。

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. 我不熟悉您所使用的Rails版本的语法,但是如果不一样的话,它可能非常相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM