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

Dee*_*k A 6 rubygems ruby-on-rails ruby-on-rails-3

我已经多次注意到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
Run Code Online (Sandbox Code Playgroud)

这是在模型目录中.

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
Run Code Online (Sandbox Code Playgroud)

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

小智 14

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

第二次它只返回存储在@method_variable中的值.

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

  • 谢谢.所以这只是为了让表现更好. (2认同)