Zheng Yan
Zheng Yan

Reputation: 3

rails controller action contain an algorithm

I have made a rails app. Users can upload images. Once the images are saved into database. An algorithm being called to process those pictures. For now, it was realized within a controller action like this:

def create
  @post = current_user.posts.build(params)
  if @post.save
    flash[:success]="post created"
    redirect_to root_url
    image_names = []
    @post.picture.each do |imgs|
      image_names << imgs.url
    end
    my_algorithm(image_names)
  else
    render 'static_pages/home'
  end
end

It works correctly. The problem is the page didn't show until the algorithm finishing. And the algorithm took long time. How to fix it. Or maybe call my_algorithm other places? Or delay_job?

Upvotes: 0

Views: 81

Answers (3)

Pasupathi Thangavel
Pasupathi Thangavel

Reputation: 942

You should try the background jobs to perform that action in particular time. You may use sidekiq gem to trigger the events in background.

Or You can refer the following URL to, do the active jobs,

http://edgeguides.rubyonrails.org/active_job_basics.html#enqueue-the-job

Refer the above url and configure the app and perform the operations in background. I have additionally mention the one more link for scheduled jobs,

How to perform a background job now?

Upvotes: 0

Kaushlendra Tomar
Kaushlendra Tomar

Reputation: 1440

I think you should use Active Job for that it will make your job background job

Upvotes: 1

Santanu
Santanu

Reputation: 960

First of all, this should be done in a call back, here in the after_create callback of the Post model. And from the callback you can en queue one delayed job or other background job which will fire the algorithm. In front end you can show some messages like under processing in the place where you want to show the processed information.

Thanks

Upvotes: 0

Related Questions