ruby-on-rails – Rails 2:Model.find(1)在id 1不存在时给出ActiveRecord错误

我使用Rails 2.3.5,如果我给Model.find(1),如果1不在数据库中,它返回ActiveRecord错误。应该只是返回nil,如在Model.find_by_column(‘..’)的情况下?
这是预期的行为。我认为大卫自己解释这是最好的,所以这里是来自Ruby,S.,Thomas,D& Hansson,D.H.,2009.Agile Web Development with Rails,第三版第三版,Pragmatic Bookshelf(p.330)。

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.

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.

http://stackoverflow.com/questions/4966430/rails-2-model-find1-gives-activerecord-error-when-id-1-does-not-exist

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:ruby-on-rails – Rails 2:Model.find(1)在id 1不存在时给出ActiveRecord错误