Ask A Question


You’re not receiving notifications from this thread.

Best practices for manipulation/working with data from model after creation

eelcoj asked in Rails

Consider the situation where a model is created to which the data needs to manipulated/worked with right after creation. For instance find (*match) a certain string from a long string, convert (parts of) the long string to PDF, upload some attachments to S3, etc.

The most obvious way to me, would be to put all this separate model's methods in a background worker.

But I was also thinking of extracting these methods into some rake task (which can then also be moved to a background queue).

Basically just curious if there are other ways to go about this. Maybe I am overthinking, but who knows (at this time of the year… ;)).


Hey Jack,

This would be a good place to write a Ruby class that handles the processing, and then you can call that class and pass in the objects you need from background workers or rake tasks. Since the class would be agnostic, you can use the background worker or rake task to feed in the inputs like the model you need to process and the work can be done in either spot with the same code. Having a rake task is easy for testing, and then background jobs are important for production tasks, so a Ruby class would let you do that nicely.

Something like this:

# Your processing class
class ProcessWhatever
  def perform(model_id)
      model = Model.find(model_id)

        # do your work here
# Your background worker can call it
class ProcessJob < ApplicationJob
  def perform(model_id)
# Rake task
task :process_whatever do

Just to +1 what Chris said - this is the perfect scenario for service objects! If you haven't already, check out his video on PORO's -

There are a ton of articles on the interwebz (keywords: ruby poro or ruby service objects) that I would strongly suggest reading since the whole idea is more about organization of code more so than core functionality once you understand how to use them.

Good luck! :)


Thanks both Chris and Jacob. Really helpful. 🙌 I got some viewing and reading to do.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 81,149+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.