rails模型类中实例变量的用途是什么

时间:2013-11-19 11:38:35

标签: ruby-on-rails ruby-on-rails-3 rubygems

我已经多次注意到rails项目程序员在模型文件中使用实例变量。我已经搜索了它的使用原因,但无法弄清楚。对于事物的上下文,我正在复制一些看起来类似于我看到的示例代码。

这是在控制器目录中。

class someController < ApplicationController
    def index
        @group = Group.find(params[:id])
        @group.method_foo  # an instance method in model class
        // some more junk code
    end
end

这是在模型目录中。

class someModel < ActiveRecord::Base
    // some relations and others defined
    def method_foo
        @method_variable ||= reference.first  # I am not so sentimental about what reference.first is, but i want to know what @method_variable is doing there.
    end
end

如果我只使用实例变量的局部变量,该怎么办?它会正常工作吗?如果有人可以帮助我,那会很有帮助。感谢。

1 个答案:

答案 0 :(得分:14)

第一次调用method_foo时,它会执行reference.first,将它的值保存在@method_variable中并返回它。

第二次它将返回存储在@method_variable中的值。

因此,如果reference.first是一项昂贵的操作,那么我们假设是一个API调用。它只会为每个实例执行一次。