Rails 控制器中出现错误时渲染什么
在我的 Rails 应用程序中,我有一个带有条目表单的部分视图。该表单包含在我的应用程序的多个页面上。部分帖子中的表单使用如下创建方法保存到 RidesController:
RidesController.rb
def create
@ride = current_user.rides.build(params[:ride])
if @ride.save
flash[:success] = "Ride created!"
redirect_to root_path
else
@rides = current_user.rides.paginate(:page => params[:page])
render 'pages/home' # <---- WHAT GOES HERE?
end
end
我已经评论了我的问题所在的行。当我们遇到错误时,我需要呈现用户当前所在的相同视图。但是因为这个控制器是从部分视图而不是完整视图调用的,所以我不知道如何判断它来自哪个上下文。
现在,如果 /rides/new 出现错误,用户最终会被重定向到也包含表单的主页。
In my rails application, I've got a partial view with an entry form on it. The form gets included on multiple pages across my app. The form in the partial posts to a RidesController to save with a create method like this:
RidesController.rb
def create
@ride = current_user.rides.build(params[:ride])
if @ride.save
flash[:success] = "Ride created!"
redirect_to root_path
else
@rides = current_user.rides.paginate(:page => params[:page])
render 'pages/home' # <---- WHAT GOES HERE?
end
end
I've commented the line where my question is. When we have an error, I need to present the same view that the user is presently on. But because this controller is being invoked from a partial instead of a full view, I don't know how to tell what context it's coming from.
Right now if there's an error on /rides/new, the user ends up redirected to the homepage which also has the form.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
执行此操作的一种方法是将模板路径与表单一起传递。
将其添加到包含表单部分的每个主视图(例如,pages/home、rides/new 等):
在您的表单部分中:
在您的控制器中:
One way you could do this is pass the template path in with the form.
Add this to each main view that includes the form partial (e.g. pages/home, rides/new, etc):
In your form partial:
In your controller: