Rails detect if request was AJAX

前端 未结 5 991
悲&欢浪女
悲&欢浪女 2020-11-28 04:21

In my action I wish to only respond with processing if it was called from an AJAX request. How do I check?

I want to do something like this:

def acti         


        
5条回答
  •  臣服心动
    2020-11-28 05:13

    I like using before_action filters. They are especially nice when you need the same filter/authorization for multiple actions.

    class MyController < AuthController
      before_action :require_xhr_request, only: [:action, :action_2]
    
      def action
        @model = Model.find(params[:id])
      end
    
      def action_2
        # load resource(s)
      end
    
      private
    
      def require_xhr_request
        redirect_to(root_url) unless request.xhr?
      end
    end
    

提交回复
热议问题