Access one model from another

I have a model method that executes the algorithm, and there is another model that, after saving, in some cases needs to be updated with the result of the algorithm.

So, I would like to do something like this:

class Model1 < ActiveRecord::Base
  after_save :update_score

  def update_score
    if ...
      ...
    else
      # run_alg from class Model2
    end
  end
end

class Model2 < ActiveRecord::Base
  def run_alg
    ...
  end
end

Is this possible, or do I need to move / copy run_algto application.rb?

+3
source share
2 answers

If it is a class method, you can just call Model2.run_alg, otherwise if it is an instance method, you need to have an instance of Model2 that can be called like @model2_instance.run_alg(where @ model2_instance is an instance variable of Model2).

Class method:

class Model2 < ActiveRecord::Base
  def self.run_alg
    ...
  end

  # or

  class << self
     def run_alg
     ...
     end
  end
end

Instance Method:

class Model2 < ActiveRecord::Base
  def run_alg
    ...
  end
end

, .

+2

Model2 instance_method, self.

class Model2 < ActiveRecord::Base
  def self.run_alg
    ...
  end
end

Model1 Model2.run_alg

+2

All Articles