A
A
Askhat Bikmetov2015-04-06 09:02:59
ruby
Askhat Bikmetov, 2015-04-06 09:02:59

How to call Mongoid model from Sidekiq?

Is it possible with Mongoid to write to MongoDB from a Sidekiq worker?

# lib/worker.rb
require 'sidekiq'
require 'model' # lib/model.rb
class AwesomeWorker
  include Sidekiq::Worker
  def perform
    RandomNumberModel.create! { random_number: Random.new.rand(1..100) }
  end
end

When running Sidekiq with such a worker, it returns an error:
uninitialized constant AwesomeWorker::RandomNumberModel

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Askhat Bikmetov, 2015-04-07
@askhat

workaround:

class AwesomeWorker
  def perform model_id
    model = ObjectSpace._id2ref(model_id.to_i)
    model.update_attributes { random_number: Random.new.rand(1..100) }
  end
end
AwesomeWorker.perform_async AwesomeModel.new.object_id

Correct solution:
class AwesomeWorker
  def perform
    ::AwesomeModel.create!  { random_number: Random.new.rand(1..100) }
  end
end

K
Kane, 2015-04-06
@Kane

Ruby has an agreement on how to name files and classes for them https://github.com/bbatsov/ruby-style-guide#naming

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question