Indicate to an ajax process that the delayed job has completed

后端 未结 3 2116
小蘑菇
小蘑菇 2020-12-15 00:25

I have a Rails 3 app that uses delayed_job to fetch some data (with a class method) when the user hits the page. How can I indicate to the ajax process that the class method

3条回答
  •  北海茫月
    2020-12-15 00:43

    Typically, the best way to do this is to store, in your database, an indication of the job's progress. For instance:

    class User
      def perform_calculation
        begin
          self.update_attributes :calculation_status => 'started'
          do_something_complex
          self.update_attributes :calculation_status => 'success' 
        rescue Exception => e
          self.update_attributes :calculation_status => 'error'
        end
      end
    end
    

    So that when you enqueue the job:

    User.update_attributes :calculation_status => 'enqueued'
    User.send_later :perform_calculation
    

    You can query, in your controller, the status of the job:

    def check_status
      @user = User.find(params[:id])
      render :json => @user.calculation_status
    end
    

    You polling ajax process can then simply call check_status to see how the job is progressing, if it has succeeded or if it has failed.

提交回复
热议问题