Rails 检测控制器中的请求类型?

发布于 2024-12-26 16:57:49 字数 514 浏览 2 评论 0原文

我有一个控制器,它通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你爱我像她 2025-01-02 16:57:50

如果它不适用于所有格式,请将检查放入格式处理程序中。或者让您重定向的路径返回对 JSON 格式有意义的内容。

在不提供任何有关请求失败原因的信息的情况下进行重定向有点对用户不利——这似乎是通过有意义的渲染而不是针对所有格式的重定向可以更好地解决的问题。

(您不需要指定应用程序布局,实际上,这是默认布局。)

针对评论的澄清(我认为):

每种格式的块就是这样:块。它们可能包含任意代码,例如:

respond_to do |format|
  format.html { @user.nil? ? redirect_to "/" : render }
  format.json { render :json => @user.to_json }
end

也许不是最干净的,部分原因是我认为这首先是错误的处理方式。

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.:

respond_to do |format|
  format.html { @user.nil? ? redirect_to "/" : render }
  format.json { render :json => @user.to_json }
end

Perhaps not the cleanest, partially because I think it's the wrong way to handle it in the first place.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文