控制器中的实例变量 [英] Instance variable in controllers

查看:49
本文介绍了控制器中的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在一个动作中定义一个实例变量时,它是否在属于同一控制器的其他动作中不可用.

When I define an instance variable in an action, is it not available inside other actions belonging to same controller.

实例变量应该在整个类中可用.对吗?

Instance variable should be available throughout the class. Right?

    class DemoController < ApplicationController

  def index
    #render('demo/hello')
    #redirect_to(:action => 'other_hello')

  end

  def hello
    #redirect_to('http://www.google.co.in')
    @array = [1,2,3,4,5]
    @page = params[:page].to_i
  end

  def other_hello
    render(:text => 'Hello Everyone')
  end

end

如果我在 index 中定义数组并从 hello 视图访问它,那么为什么我会收到错误值 nil 的错误?

If I define the array in index and access it from hello view then why am I getting errors for false values of nil?

推荐答案

实例变量仅在请求(控制器和视图渲染)期间可用,因为 Rails 为每个请求创建一个新的控制器实例.

The instance variables are available only during the request (controller and view rendering), because Rails create a new instance of controller for each request.

如果您想在请求之间保留数据,请使用 sessions.

If you want to keep data between request, use sessions.

这篇关于控制器中的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆