如何在轨控制器处理的ActiveRecord :: RecordNotFound? [英] how to handle ActiveRecord::RecordNotFound in rails controller?
本文介绍了如何在轨控制器处理的ActiveRecord :: RecordNotFound?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有用户和活动的应用程序。每个用户有几个事件。当用户希望看到一个特定的事件,他会得到这个动作:
I have an app with user and events. Each user has several events. When a user wants to see a specific event he will get to this action:
def show
begin
@userEvents = current_user.event
@event = @userEvents.find(params[:id])
rescue ActiveRecord::RecordNotFound
redirect_to :controller => "main", :action => "index"
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: @event }
end
end
如果没有找到它意味着他的URL,他正在试图让不属于他的情况下打了用户的事件。我想要么他重定向到主页或只是未找到事件的错误显示页面。如果我尝试运行上面这个错误火灾code:
If the event is not found for the user it means he played with the URL and the event he is trying to get does not belong to him. I want to either redirect him to the main page or just display the page with an error that the event is not found. If I try to run the code above this error fires:
AbstractController::DoubleRenderError in EventsController#show
什么是解决这个问题的最好方法是什么?
What's the best way to fix this?
推荐答案
把的返回的重定向之后
begin
@userEvents = current_user.event
@event = @userEvents.find(params[:id])
rescue ActiveRecord::RecordNotFound
redirect_to :controller => "main", :action => "index"
return
end
这篇关于如何在轨控制器处理的ActiveRecord :: RecordNotFound?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文