在控制器实例变量(Instance variable in controllers)

2019-11-01 07:54发布

当我在一个动作定义一个实例变量,是不是可以属于同一控制其他行动中。

实例变量应该在整个类是可用的。 对?

    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

如果我定义的索引以及访问它的阵列来自Hello观点,为什么我收到了零的假值的误差?

Answer 1:

实例变量仅在请求(控制器和视图渲染)是可用的,由于Rails为每个请求创建控制器的新实例。

如果你想请求之间保留的数据使用会话 。



Answer 2:

如果定义在一个实例变量index的行动,也只会是在动作用。 如果要定义相同的实例变量的两个动作,你可以做两件事情之一:

def index
  set_instance_array
  ...
end

def hello
  set_instance_array
  ...
end

...

private
def set_instance_array
  @array = [1,2,3,4,5]
end

如果你这样做了很多,你可以过滤器之前使用:

class DemoController < ApplicationController
  before_filter :set_instance_array

  def index
    ...
  end
  ...
end

这就需要每个请求之前set_instance_array方法。 见http://guides.rubyonrails.org/action_controller_overview.html#filters获取更多信息。



文章来源: Instance variable in controllers