是否可以执行以下操作:
if @user = User.friendly.find(params[:id])
// logic here
else
// do something if user doesn't exist
end
由于某种原因,这会引发以下错误:
ActiveRecord::RecordNotFound
最佳答案
[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 thefind_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]
关于ruby-on-rails - rails : check if ID doesn't exist in controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821191/