Rails 2:当 id 1 不存在时,Model.find(1) 给出 ActiveRecord 错误 [英] Rails 2: Model.find(1) gives ActiveRecord error when id 1 does not exist

查看:19
本文介绍了Rails 2:当 id 1 不存在时,Model.find(1) 给出 ActiveRecord 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Rails 2.3.5,如果我给出 Model.find(1) 并且如果 1 不在数据库中,它会返回 ActiveRecord 错误.它应该像 Model.find_by_column('..') 那样返回 nil 吗?

I am using Rails 2.3.5 and in that if I give Model.find(1) and if 1 is not in the database, it returns ActiveRecord error. Should it just be returning nil as in the case of Model.find_by_column('..')?

推荐答案

这是预期的行为.我认为大卫本人对此解释得最好,所以这里引用了 Ruby, S.、Thomas, D. &Hansson,DH,2009 年.使用 Rails 进行敏捷 Web 开发,第三版,第三版.,实用书架(第 330 页).

This is the expected behavior. I think David explains this the best himself, so here is a quote from Ruby, S., Thomas, D. & Hansson, D.H., 2009. Agile Web Development with Rails, Third Edition Third Edition., Pragmatic Bookshelf (p.330).

当您使用由主键,你正在寻找一个具体记录.你期望它存在.对 Person.find(5) 的调用是基于我们对人民的了解桌子.我们想要 id 为的行5.如果这次调用不成功——如果id为5的记录已经被被摧毁——我们正处于特殊时期情况.这要求提高一个例外,所以 Rails 引发记录不存在.

When you use a finder driven by primary keys, you’re looking for a particular record. You expect it to exist. A call to Person.find(5) is based on our knowledge of the people table. We want the row with an id of 5. If this call is unsuccessful—if the record with the id of 5 has been destroyed—we’re in an exceptional situation. This mandates the raising of an exception, so Rails raises RecordNotFound.

另一方面,使用条件进行搜索的发现者正在寻找比赛.所以,Person.find(:第一个,:conditions=>"name='Dave'") 是相当于告诉数据库(如一个黑匣子)给我第一个人名为 Dave 的行."这个表现出截然不同的检索方法;我们不确定我们会得到结果.结果集完全有可能可能是空的.因此,在搜索者的情况一行和一个空数组用于查找器搜索多行是自然的、非异常的反应.

On the other hand, finders that use criteria to search are looking for a match. So, Person.find(:first, :conditions=>"name=’Dave’") is the equivalent of telling the database (as a black box) "Give me the first person row that has the name Dave." This exhibits a distinctly different approach to retrieval; we’re not certain up front that we’ll get a result. It’s entirely possible the result set may be empty. Thus, returning nil in the case of finders that search for one row and an empty array for finders that search for many rows is the natural, nonexceptional response.

这篇关于Rails 2:当 id 1 不存在时,Model.find(1) 给出 ActiveRecord 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆