Rails 检测控制器中的请求类型?
我有一个控制器,它通过 html 显示用户个人资料,通过 JSON 显示用户悬停卡和个人资料信息。
class UsersController < ApplicationController
def show
@user = User.where(:id => params[:id]).first
return redirect_to "/" if @user.nil?
respond_to do |format|
format.html { render :layout => 'application' }
format.json { render :json => @user.to_json }
end
end
end
问题是,当找不到用户时,它会进行重定向,这在 HTML 中效果很好,但在 JSON 中会导致错误。有没有一种干净的方法可以让重定向仅在 HTML 请求时发生?什么是正确的、干净的方式来处理这个问题?
谢谢
I have a controller which via html shows the user profile, via JSON shows a user hover card w profile info.
class UsersController < ApplicationController
def show
@user = User.where(:id => params[:id]).first
return redirect_to "/" if @user.nil?
respond_to do |format|
format.html { render :layout => 'application' }
format.json { render :json => @user.to_json }
end
end
end
The problem is when the user is not found it redirects which works great in via HTML but causes errors with JSON. Is there a clean way to have the redirect only happen if it is a HTML request? What's the right rails, clean way to handle this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果它不适用于所有格式,请将检查放入格式处理程序中。或者让您重定向的路径返回对 JSON 格式有意义的内容。
在不提供任何有关请求失败原因的信息的情况下进行重定向有点对用户不利——这似乎是通过有意义的渲染而不是针对所有格式的重定向可以更好地解决的问题。
(您不需要指定应用程序布局,实际上,这是默认布局。)
针对评论的澄清(我认为):
每种格式的块就是这样:块。它们可能包含任意代码,例如:
也许不是最干净的,部分原因是我认为这首先是错误的处理方式。
Put the check in the format handler if it's not applicable to all formats. Or have the path you redirect to return something meaningful for a JSON format.
It's somewhat user-hostile to redirect without providing any information regarding why the request failed--this seems a problem better solved by meaningful rendering rather than a redirect for all formats.
(You don't need to specify the application layout, really, it's the default.)
Clarification in response to comment (I think):
The blocks for each format are just that: blocks. They may contain arbitrary code, e.g.:
Perhaps not the cleanest, partially because I think it's the wrong way to handle it in the first place.