2013-01-02 75 views
0

當我在動作中定義實例變量時,是否在屬於同一控制器的其他動作中不可用。控制器中的實例變量

實例變量應在整個課程中提供。對?

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 

如果我定義從你好鑑於指數數組和訪問它,那麼爲什麼我會收到錯誤的零的假值?

回答

4

實例變量僅在請求(控制器和視圖呈現)期間可用,因爲Rails爲每個請求創建一個新的控制器實例。

如果要在請求之間保留數據,請使用sessions

0

如果您在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

相關問題