为什么我的RESTful API返回404?

时间:2014-07-23 23:07:33

标签: ruby-on-rails ruby rest http-status-code-404

我正在Rails中构建REST API,并且无法解释以下代码段的观察行为:

  #GET /:id/user
  def find_user
    if params.has_key?(:id)
      @user = User.find(params[:id])

      if @user.present?
        respond_to do |format|
          response = {:status => "200",
                      :message => "Successfully found user.",
                      :first_name => @user.first_name,
                      :last_name => @user.last_name}

          format.json { render json: response, status: :ok }
        end
      else
        respond_to do |format|
          response = {:status => "422", :message => "Failed to get user."}
          format.json { render json: response, status: :unprocessable_entity}
        end
      end
    else
      respond_to do |format|
        response = {:status => "422", :message => "Failed to get user."}
        format.json { render json: response, status: :unprocessable_entity}
      end
    end
  end

此方法代表API端点,可通过以下网址http://localhost:3000/api/52/user访问。

这似乎有效,当请求具有有效ID的用户时,API会正确响应。

当请求具有无效ID的用户时,问题就出现了,即http://localhost:3000/api/NotAnId/user)。

我在我的方法中设置了如果搜索用户对象并且没有找到任何内容422 unprocessable entity作为状态代码返回,但由于某种原因它总是返回404。为什么每次使用无效的用户ID搜索用户时,都会返回404而不是422?为什么我的代码被覆盖了?

1 个答案:

答案 0 :(得分:1)

因为User.find(params[:id])如果找不到记录就会提升RecordNotFound,如果你为User.find_by_id(params[:id])更改了它,它将按预期工作

实际上,如果

,您只能使用一个代码清理代码
#GET /:id/user
def find_user
  @user = User.find_by_id(params[:id])
  if @user
    response = {:status => "200",
      :message => "Successfully found user.",
      :first_name => @user.first_name,
      :last_name => @user.last_name
    }
    render json: response, status: :ok 
  else
    response = {:status => "422", :message => "Failed to get user."}
    render json: response, status: :unprocessable_entity
  end
end
相关问题