Ruby on rails 找不到Rails通用控制器方法
在我的控制器中,我的一个操作中包含以下代码:Ruby on rails 找不到Rails通用控制器方法,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,在我的控制器中,我的一个操作中包含以下代码: begin @user = User.find(params[:id]) @user.destroy rescue ActiveRecord::RecordNotFound render :json => {"status" => "404", "message" => "User with id #{params[:id]} not found"} return end 并且工作正常,但我不想将其复制粘贴到运行S
begin
@user = User.find(params[:id])
@user.destroy
rescue ActiveRecord::RecordNotFound
render :json => {"status" => "404", "message" => "User with id #{params[:id]} not found"}
return
end
并且工作正常,但我不想将其复制粘贴到运行Select查询所需的所有方法
所以我找到了这个答案
然后尝试稍微不同,因为我呈现的是JSON API端点,而不是模板。
请注意,我也不知道是否会在那里定义params[:id]
def not_found
render :json => {"status" => "404", "message" => "User with id #{params[:id]} not found"}
end
无论如何,我用以下命令修改了查询:
@user = User.find(params[:id]) or not_found
但仍在引发ActiveRecord::RecordNotFound异常
还有可能创建一个通用的not_found操作,我可以在所有控制器中使用它,我可以将id参数和对象类型传递给它
像一些普通的404、500、400、200方法一样,这些方法呈现JSON响应,我只需在其中传递一些参数即可使用ApplicationController中的rescue\u:
class ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :show_not_found_errors
# All the information about the exception is in the parameter: exception
def show_not_found_errors(exception)
render json: {error: exception.message}, status: :not_found
end
end
因此,任何ActiveRecord::RecordNotFound都将使用show\u not\u found\u errors方法进行解救。在ApplicationController中添加这些代码,它将适用于从ApplicationController继承的所有其他控制器。在ApplicationController中使用rescue\u:
class ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :show_not_found_errors
# All the information about the exception is in the parameter: exception
def show_not_found_errors(exception)
render json: {error: exception.message}, status: :not_found
end
end
因此,任何ActiveRecord::RecordNotFound都将使用show\u not\u found\u errors方法进行解救。在ApplicationController中添加这些代码,它将适用于从ApplicationController继承的所有其他控制器。感谢您的回复!对于您的代码,当找不到对象时,我现在收到一个空JSON,我是否应该用我的代码替换render JSON:exception,status::not_found?我明白了,有没有办法将此代码扩展到我应用程序的所有控制器?或者我必须在所有对象中定义它们。@lapinkoira只是在ApplicationController中,检查我的更新。好的,您认为可以检测出引发异常的对象类型吗?所以它可以写下找不到的用户。。。找不到集合。。。etcAll您需要的信息在params:exception中,它是ActiveRecord::RecordNotFound的一个实例,请尝试exception.message作为我的更新。谢谢您的回复!对于您的代码,当找不到对象时,我现在收到一个空JSON,我是否应该用我的代码替换render JSON:exception,status::not_found?我明白了,有没有办法将此代码扩展到我应用程序的所有控制器?或者我必须在所有对象中定义它们。@lapinkoira只是在ApplicationController中,检查我的更新。好的,您认为可以检测出引发异常的对象类型吗?所以它可以写下找不到的用户。。。找不到集合。。。etcAll您需要的信息在params:exception中,它是ActiveRecord::RecordNotFound的实例,请尝试使用exception.message作为我的更新。