I have a model method that performs an algorithm, and there is another model that, after saving, in some cases, needs to refresh the algorithm result.
So, I would like to be able to do something like this:
class Model1 < ActiveRecord::Base
after_save :update_score
def up开发者_Go百科date_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 have to move/copy run_alg
into application.rb?
If it is a class method, you can just call Model2.run_alg
, otherwise if it's an instance method you need to have an instance of Model2, which 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
To read more on class methods and instance methods, check this out.
Change method in your Model2
to instance_method
by adding self.
class Model2 < ActiveRecord::Base
def self.run_alg
...
end
end
And call it from Model1
as Model2.run_alg
精彩评论