ruby-on-rails - rails : check if ID doesn't exist in controller?

标签 ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 friendly-id

是否可以执行以下操作:

if @user = User.friendly.find(params[:id])
    // logic here
else
    // do something if user doesn't exist
end

由于某种原因,这会引发以下错误:

ActiveRecord::RecordNotFound

最佳答案

This is as expected .

[The] RecordNotFound [exception is raised if] 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 [like the find_by* methods] do not raise this exception to signal nothing was found ..

使用find_by_id(或find_by),如果未找到该项目,将返回nil:

friendly.find_by_id params[:id]
friendly.find_by id: params[:id]

另请参阅:Rails find getting ActiveRecord::RecordNotFound

关于ruby-on-rails - rails : check if ID doesn't exist in controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821191/

相关文章:

ruby-on-rails - 两个数组的交集为空

ruby - 真正的轮胎方法的代理?

ruby-on-rails - 在 ruby​​ 中使用 Markdown 处理 wiki 链接

ruby-on-rails - Rails 回形针 URL 上传问题及如何使其 DRY

ruby-on-rails - 在 DreamHost 上带有 rails 3 应用程序的 internal_error.html

ruby-on-rails - Devise 2.1默认是关闭盐的吗?

ruby-on-rails - Rails 模型 - 更新 JSON 中的嵌套键/值

ruby - Win3 2's FindWindow() can find a particular window with the exact title, but what about "try.bat - 记事本”?

ruby-on-rails-3 - Sqlite3 : Failed to build gem native extension

ruby - Heroku,设计 : Getting 'NoMethodError (undefined method ` to_key' for :user:Symbol)'