gpt4 book ai didi

ruby-on-rails - Rails 异常不适用于 find_by 查询

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:11 25 4
gpt4 key购买 nike

异常处理不适用于 rails 中的 find_by 查询 这里的代码:

  ab = User.find_by_uniq_token(params[:uniq_token])

不引发异常...同时:

  ab = User.find(:id)  # is working fine...

我在应用程序 Controller 中有异常处理代码,例如:

  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found


def record_not_found
if current_user
flash[:notice] = "Record not found "
redirect_to authenticated_root_url
else
flash[:notice] = "Record not found ."
redirect_to unauthenticated_root_url
# Assuming you have a template named 'record_not_found'
end
end

最佳答案

如果没有找到记录,您需要使用等效的 bang (!) 方法来引发异常。

ab = User.find_by_uniq_token!(params[:uniq_token])

ab = User.where(uniq_token: params[:uniq_token]).first!

关于ruby-on-rails - Rails 异常不适用于 find_by 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30396134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com