Rails 发现获取 ActiveRecord::RecordNotFound [英] Rails find getting ActiveRecord::RecordNotFound
问题描述
我有一张表,其中包含模型中的属于".该表包含用于链接两个表的 xx_id 字段.
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 会是空白的.当它是时,我得到 ActiveRecord::RecordNotFound.我不想要错误 - 我只想要这个字段的空白显示.
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.
你有什么建议?
推荐答案
Rails 在您使用 find
方法时总是会引发 ActiveRecord::RecordNotFound 异常.但是,find_by_*
方法在没有找到记录时返回 nil
.
Rails will always raise an ActiveRecord::RecordNotFound exception when you use the find
method. The find_by_*
methods, however, return nil
when no record is found.
ActiveRecord 文档告诉我们:
RecordNotFound - 没有记录响应 find 方法.无论是具有给定 ID 的行不存在或该行不符合额外的限制.某些查找调用不会引发此异常表示未找到任何内容,请检查其文档更多详情.
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.
如果您想在找不到记录时返回nil
,只需按如下方式处理异常:
If you'd like to return nil
when records cannot be found, simply handle the exception as follows:
begin
my_record = Record.find params[:id]
rescue ActiveRecord::RecordNotFound => e
my_record = nil
end
这篇关于Rails 发现获取 ActiveRecord::RecordNotFound的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!