ruby-on-rails - rails 3.2.0 仅当它是 json 格式时才在过滤器之前跳过

标签 ruby-on-rails json authentication ruby-on-rails-3.2

1. skip_before_filter :authorize, :only => [:index,:show], :if => proc {|c| request.json?}

2. skip_before_filter :authorize, :only => [:index,:show], :if => :format_json?

    def format_json?
      request.format.json?
    end   

3. skip_before_filter :authorize, :only => [:index, :show] , :if =>request.content_type == "json"
for the first request it is showing:
    #undefined local variable or method `request' for ExamsController:Class
If i refresh the page it is not skipping anyting 

仅当请求内容为 json 时,我才想跳过“索引”和“显示”操作的身份验证。我试过上面的例子,但没有任何效果。任何建议都会有所帮助。

最佳答案

class XXXXController < ApplicationController
  skip_before_filter :authorize, :only => [:index,:show], if: :json_request?

  #your other actions here. 

  private 
  def json_request?
    request.format.symbol == :json
  end
end

在我的例子中,我尝试了以下对我的操作的调用,并且格式被验证为 :json 类型:

$(document).on('ready', function(){

   $('body').on('submit', '#new_job', function(e){
    e.preventDefault();

    $.ajax({
      dataType: "json",
      url: '/jobs/',
      type: 'post',
      success: function(data){
        console.log("registered success");
      },
      failure: function(error){
        console.log("This is the failure block ");
      }
    });
   });
});

enter image description here

关于ruby-on-rails - rails 3.2.0 仅当它是 json 格式时才在过滤器之前跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28271566/

相关文章:

authentication - 为什么API网关和认证服务应该不同?

asp.net - Windows Server 2008、IIS7 和 Windows 身份验证

ruby-on-rails - 在 View 中显示缺失的 I18n 翻译

ruby-on-rails - 为什么我的创建表单不起作用,甚至没有响应?

java - 如何将json添加到GET请求查询参数中?

javascript - 为什么 vue.js 组件在第一次尝试时不显示获取的数据?

ruby-on-rails - 在 centos 中找不到 ruby​​ 1.8.7 的文件 extconf.rb?

mysql - Ruby 事件记录在 mysql 中插入日期时间而不是时间

javascript - 如何检查 JSON 对象数组是否包含数组中定义的值?

ios - 使用 STTwitterAPI 使用 twitter 登录一次