Ruby-on-rails Rails 发现获取 ActiveRecord::RecordNotFound
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9709659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails find getting ActiveRecord::RecordNotFound
提问by Reddirt
I have a table that includes a "belongs to" in the model. The table includes the xx_id field to link the two tables.
我有一张表,其中包含模型中的“属于”。该表包括用于链接两个表的 xx_id 字段。
But, sometimes the xx_id is going to be blank. When it is, I get ActiveRecord::RecordNotFound. I don't want an error - I just want a blank display for this field.
但是,有时 xx_id 将是空白的。当它是时,我得到 ActiveRecord::RecordNotFound。我不想要错误 - 我只想要这个字段的空白显示。
What do you suggest?
你有什么建议?
回答by Graham Swan
Rails will always raise an ActiveRecord::RecordNotFoundexception when you use the findmethod. The find_by_*methods, however, return nilwhen no record is found.
当您使用该方法时,Rails 将始终引发ActiveRecord::RecordNotFound异常find。find_by_*然而,这些方法nil在没有找到记录时返回。
The ActiveRecord documentationtells us:
该ActiveRecord的文档告诉我们:
RecordNotFound - No record responded to the find method. Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions. Some find calls do not raise this exception to signal nothing was found, please check its documentation for further details.
RecordNotFound - 没有记录响应 find 方法。具有给定 ID 的行不存在或该行不符合附加限制。某些 find 调用不会引发此异常以表示未找到任何内容,请查看其文档以获取更多详细信息。
If you'd like to return nilwhen records cannot be found, simply handle the exception as follows:
如果您想nil在找不到记录时返回,只需按如下方式处理异常:
begin
my_record = Record.find params[:id]
rescue ActiveRecord::RecordNotFound => e
my_record = nil
end
回答by dennismonsewicz
Can't you write
你不能写吗
my_record = Record.find(params[:id]) rescue nil
回答by Sergey Sokolov
Record.find_by(id: params[:id])
returns Recordobject if it is found or nil if it is not.
Record如果找到则返回对象,否则返回nil。
回答by mikowiec
When you call find, you'll obtain an array. When array does not contain objects, count is zero.
当您调用 find 时,您将获得一个数组。当数组不包含对象时,计数为零。
items = Store.find(:all, :conditions => {:resource_id => item.id})
if item.count == 0 puts " !not found for item id#{item.id}"
or
或者
if item.nil? puts " !not found for item id#{item.id}"

