Search code examples
ruby-on-railsrubyruby-on-rails-4sidekiqresque

How do you refer an instance of a model in model class in Ruby on Rails?


I'm trying to refer an instance of User class in a Rails for geocoding

class User < ActiveRecord::Base
  geocoded_by :address

  after_validation GeocodeJob.perform_later(self), if: :address_changed?
end

What I'm trying to pass on is the current instance of user. However as it is obvious, what I'm ending up passing is the class and not the instance, failing starting my job queue.

How can I refer and pass the user instance on a model callback? I know I can use instance variables using a controller, wondering if I can queue directly as a model callback.


Solution

  • With what you have currently written, GeocodeJob.perform_later(self) will be called when the class is loaded and it's return value will be used as the parameter passed to the call to after_validation. As you say, that's not what you want.

    Instead, you can pass a symbol for a method to call like so:

    class User < ActiveRecord::Base
      geocoded_by :address
    
      after_validation :setup_geocode_job, if: :address_changed?
    
      def setup_gecode_job
        GeocodeJob.perform_later(self)
      end
    end
    

    This will do what you want by calling the instance method of the model and self will be the model instance.

    See: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html