Rails

How To Perform Some Task After View Render Using Threads In Rails

Posted by Weston Ganger on July 21, 2016

I wanted an easy way to run some expensive tasks after my controller rendered the view so that the user can continue on while the work is done. While most of the time you can use ActiveJob or something to do this, this technique can come in handy.

Turns out we can easily do this by creating a new Thread. Here I show using with render or redirect_to


class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
    render
    Thread.new do
      my_expsenive_method(@post)
    end
  end
  
  def update
    @post = Post.find(params[:id])
    @post.update_attributes(post_params)
    redirect_to action: :index
    Thread.new do
      my_expsenive_method(@post)
    end
  end
end

This works like a charm however this technique should only be used in non-critical code because Threads have many quirks to them. For example you will not easily be able get any data back from this new thread and it also will not show any errors to your users if it fails.


Related External Links:


Posted in Rails and Tagged with thread 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts