Ruby on rails 控制器中http引发错误的rails约定?
假设我有一个带有show方法的控制器 我希望确保只有具有有效许可证代码的客户端才能读取此控制器操作的json端点Ruby on rails 控制器中http引发错误的rails约定?,ruby-on-rails,http,model-view-controller,exception-handling,Ruby On Rails,Http,Model View Controller,Exception Handling,假设我有一个带有show方法的控制器 我希望确保只有具有有效许可证代码的客户端才能读取此控制器操作的json端点 def show authenticate_license if params[:format] == 'json' # boilerplate respond_to do |format| format.html format.json { render json: @article, status: :ok } end end 我可能想在其他地
def show
authenticate_license if params[:format] == 'json'
# boilerplate
respond_to do |format|
format.html
format.json { render json: @article, status: :ok }
end
end
我可能想在其他地方使用这个身份验证块,所以我把它放在我的应用程序\u控制器中
# in application_controller
def authenticate_license
@client = params[:client]
licenses = License.where(:code => params[:code])
@license = licenses.first
if @license
if @license.client = @client
# do nothing, we're fine
else
respond_to do |format|
format.json { render json: 'wrong client', status: 400 }
end
end
else
respond_to do |format|
format.json { render json: 'bad license', status: :forbidden }
end
end
end
但是这会产生一个双重渲染器,所以现在我将尝试一些不同的方法
# in application_controller
def authenticate_license
licenses = License.where(:code => params[:code]
@license = licenses.first
if @license
if @license.client = @client
# do nothing, we're fine
else
raise ActionController::RoutingError.new('wrong client')
end
else
raise ActionController::RoutingError.new('bad license code')
end
end
rescue_from ActionController::RoutingError do |exception|
respond_to do |format|
format.html { redirect_to root_url, :alert => exception.message }
format.json { render json: exception.message, status: :forbidden }
end
end
但是这样,我不能指定HTTP状态,而且我还捕获了可能不想捕获的路由错误
做我想做的事的正确方法是什么
我所描述的行为和Desive差不多。如果您向具有授权用户的操作发出请求!方法,它将引发错误,并将用户重定向到某个页面。CanCan也会执行类似的操作,如果用户未被授权执行某些操作,它会引发您应该捕获的自身异常。错误有效,您渲染了不止一次,这就是出现
doublerender
异常的原因。最好仅在控制器中保持渲染
试试这个代码
def show
is_client_valid = authenticate_license if params[:format] == 'json'
# boilerplate
respond_to do |format|
format.html
if is_client_valid == 'valid' #you can have a switch statement here, so that you can easily set the status tag
format.json { render json: @article, status: :ok }
else
format.json { render json: is_client_valid }
end
end
end
# in application_controller
def authenticate_license
@client = params[:client]
licenses = License.where(:code => params[:code])
@license = licenses.first
if @license
if @license.client = @client
return 'valid'
else
return 'wrong client'
end
else
return 'bad licence'
end
end
“客户端_有效吗”。。。那是打字错误吗?或者ruby/rails是否有“is”关键字。。。?