How to Use Active Job in Rails: Simple Guide with Examples
In Rails, use
Active Job by creating a job class that inherits from ApplicationJob and defining a perform method with the task code. Then enqueue the job with perform_later to run it asynchronously in the background.Syntax
To use Active Job, create a job class inheriting from ApplicationJob. Define a perform method with the code you want to run in the background. Use perform_later to enqueue the job asynchronously.
- class YourJob < ApplicationJob: Defines the job class.
- perform(*args): Contains the background task code.
- perform_later(*args): Enqueues the job to run later.
ruby
class ExampleJob < ApplicationJob queue_as :default def perform(*args) # Your background task code here end end # To enqueue the job: ExampleJob.perform_later('argument')
Example
This example shows a job that sends a welcome email asynchronously. The perform method calls the mailer, and perform_later queues the job.
ruby
class WelcomeEmailJob < ApplicationJob queue_as :default def perform(user_id) user = User.find(user_id) UserMailer.welcome_email(user).deliver_now end end # Enqueue the job to send email later WelcomeEmailJob.perform_later(1)
Output
The job is enqueued and the welcome email is sent in the background without blocking the main app flow.
Common Pitfalls
Common mistakes include calling perform directly instead of perform_later, which runs the job immediately and blocks the request. Another is forgetting to configure a queue adapter, so jobs never run.
Always set a queue adapter like config.active_job.queue_adapter = :async in config/application.rb or use a production-ready adapter like Sidekiq.
ruby
class BadJob < ApplicationJob def perform puts 'This runs immediately, blocking the request' end end # Wrong: runs immediately BadJob.perform # Right: runs in background BadJob.perform_later
Quick Reference
| Action | Code Example | Description |
|---|---|---|
| Create job class | class MyJob < ApplicationJob; def perform; end; end | Defines a background job |
| Enqueue job | MyJob.perform_later(args) | Runs job asynchronously |
| Run job immediately (not recommended) | MyJob.perform(args) | Runs job synchronously |
| Set queue adapter | config.active_job.queue_adapter = :sidekiq | Configures job backend |
| Define queue | queue_as :mailers | Assigns job to a specific queue |
Key Takeaways
Create jobs by inheriting from ApplicationJob and defining perform method.
Use perform_later to enqueue jobs for background execution.
Configure a queue adapter to ensure jobs run properly.
Avoid calling perform directly to prevent blocking requests.
Assign jobs to queues for better organization and processing.