当我访问控制器中的不同操作时,实例变量会重置吗?

AZ.*_*AZ. 1 ruby ruby-on-rails

我认为@user是一个实例变量,应该在访问 后设置localhost://users/1,现在如果我导航到localhost://users/new,为什么@user是 nil?

class UsersController < ApplicationController
  def new
    # normally you would create a new model and assign it to the instance variable,
    # but if I comment it out, why is it nil instead of keeping the value from show action?
    # @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end
end
Run Code Online (Sandbox Code Playgroud)

Joh*_*ohn 5

实例变量仅在请求期间“有效”。在每个请求期间都会创建控制器类的新实例。因此,如果您访问显示页面,则会使用调用的显示方法创建控制器的实例。当您访问 new 时,当前控制器将被销毁,并创建一个新控制器并调用新方法。

  • @AZ http://guides.rubyonrails.org/action_controller_overview.html “举个例子,如果用户在应用程序中转到 /clients/new 添加新客户端,Rails 将创建 ClientsController 的实例并运行新方法”。 (2认同)