如何从Ruby on Rails应用程序返回正确的HTTP错误代码

Ale*_*vin 31 ruby ruby-on-rails http

我有RoR 3.0 Web应用程序,它充当OAuth API提供程序.现在,在API中我想向API使用者返回正确的HTTP错误代码.我该怎么做呢?

这是一个例子:

def destroy_oauth
    @item = Item.find(params[:id])
    if(!@item.nil? && @item.user_id == current_user.id)
        @item.destroy
        respond_to do |format|
                format.js
                format.xml
        end
    else
        raise ActionController::RoutingError.new('Forbidden')
    end
end
Run Code Online (Sandbox Code Playgroud)

因此,如果出现错误,我正在尝试返回Forbidden 403代码.仍然,当运行这个时,我总是得到404 Not Found返回.如何返回正确的代码?

或者这是某种网络服务器可配置的东西?

Fre*_*ung 54

如果您只是提供状态代码并且没有正文,那么便捷的方式就是

head 403
Run Code Online (Sandbox Code Playgroud)

此方法还接受状态代码的符号名称,例如

head :forbidden
Run Code Online (Sandbox Code Playgroud)


San*_*ing 45

您应该以正确的状态呈现页面.

render(:file => File.join(Rails.root, 'public/403.html'), :status => 403, :layout => false)
Run Code Online (Sandbox Code Playgroud)

  • 作为旁注,这里指定的`.html`扩展名已弃用(请参阅https://github.com/rails/rails/issues/7288上的讨论),因此我们应该使用`render(:file => File.join(Rails.root,'public/403'),: formats => [:html],:status => 403,:layout => false)`(请注意我指定格式的方式). (2认同)

ger*_*tas 12

根据ActionController :: Head文档,只需在动作中使用此模式

  return head([status]) if/unless [some condition here]
Run Code Online (Sandbox Code Playgroud)

例:

  return head(:gone) if @record.deleted?
  return head(:forbidden) unless @user.owns?(@record)
Run Code Online (Sandbox Code Playgroud)

return 用于确保将不会运行操作中的剩余代码.