从另一个模型访问一个模型 [英] Accessing one model from another
问题描述
我有一个执行算法的模型方法,还有另一种模型,在某些情况下,保存后需要刷新算法结果.
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 update_score
if ...
...
else
# run_alg from class Model2
end
end
end
class Model2 < ActiveRecord::Base
def run_alg
...
end
end
这可能吗?还是我必须将run_alg
移动/复制到application.rb中?
Is this possible or do I have to move/copy run_alg
into application.rb?
推荐答案
如果是类方法,则可以调用Model2.run_alg
;否则,如果您是实例方法,则需要具有Model2的实例.称为@model2_instance.run_alg
(其中@ model2_instance是Model2的实例变量).
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方法:
class Model2 < ActiveRecord::Base
def self.run_alg
...
end
# or
class << self
def run_alg
...
end
end
end
实例方法:
class Model2 < ActiveRecord::Base
def run_alg
...
end
end
要详细了解类方法和实例方法,请检查一下.
To read more on class methods and instance methods, check this out.
这篇关于从另一个模型访问一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!