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