Can't Find ModelName With Id = 12345

Very often we use Callbacks to perform several actions after creation of a record. Also sometimes make a queue for SideKiq workers to work on. Let’s assume a model User.

user.rb
1
2
3
4
5
6
7
8
9
10
class User < ActiveRecord::Base

  # ===== Call Backs ==== #
  after_create :do_some_action

  def do_some_action
      UserSetupWorker.perform_async(self.id)
  end

end

and worker

Worker.rb
1
2
3
4
5
6
7
class Worker

  def perform(user_id)
      User.find(user_id)
  end

end

But some times we get error like Can't find User with id = XX. To avoid this —

user.rb
1
2
3
4
5
6
7
8
9
10
class User < ActiveRecord::Base

  # ===== Call Backs ==== #
  after_commit :do_some_action, :on => :create

  def do_some_action
      UserSetupWorker.perform_async(self.id)
  end

end

This way there would be no error for Can't find User with id = XX in any case. More details check Rails Best Practices.

Comments