【发布时间】:2016-04-30 20:07:33
【问题描述】:
我是 json 新手,返回时遇到问题。我得到下面的错误,即使我到处都是render,我也是return。是什么导致了这个错误?
Api::V1::ArticlesController#show 中的AbstractController::DoubleRenderError
在此操作中多次调用渲染和/或重定向。
错误是指下面def authenticate_user中的render json: {errors: "not authorized" }, status: :unauthorized。相反,我希望它只会呈现一个 json 错误:“未授权”。知道为什么这没有发生吗?
before_action :authenticate
def authenticate
unless authenticated?
render json: {errors: "not authorized" }, status: :unauthorized
return
end
end
这会调用以下辅助方法:
def authenticated?
!current_user.nil?
end
def current_user
token = request.headers["Authorization"]
email = request.headers["HTTP_USER_EMAIL"]
if token
user = User.friendly.find_by(email: email)
if user
if user.token_expired?
render json: {errors: "Session expired, please login" }, status: :unauthorized
return
elsif user.authenticated?(token)
@current_user = user
end
end
else
nil
end
end
更新: 为在任何地方删除 return 提供的解决方案都有效,但我不明白为什么。假设辅助方法如下所示。那么包含return 很重要,对吧?因为否则如果找不到@node,该方法仍将继续,并且不会显示消息“找不到节点”。你能解释一下吗?
def create
@node = Node.find_by(id: params[:node_id])
if @node.nil?
render json: { errors: "node not found" }, status: :bad_request
return
end
nodee = @node.create(create_params)
if nodee.save
render json: @node, status: :created
else
render json: @node, status: :bad_request
end
end
换句话说,我原以为从def authenticate 中删除render 会导致Rails 继续使用create 方法,因为def authenticate 没有告诉它到那里(这就是我见render)。
Update2:我也不能按照答案中的建议删除render,而是将其移至行首:return render json: {errors: "not authorized" }, status: :unauthorized。很想知道这是为什么。
【问题讨论】:
-
从
authenticate方法中移除return -
从您的
authenticate方法和current_user方法中删除return。 -
谢谢,删除
render有效。但我不明白。您能否看看添加到 OP 中的更新?
标签: ruby-on-rails ruby json ruby-on-rails-4 rendering