Reputation: 5221
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
If I define the array in index and access it from hello view then why am I getting errors for false values of nil?
Upvotes: 0
Views: 4461
Reputation: 3766
If you define an instance variable in the index
action, it will only be available in that action. If you want to define the same instance variable for two actions, you can do one of two things:
def index
set_instance_array
...
end
def hello
set_instance_array
...
end
...
private
def set_instance_array
@array = [1,2,3,4,5]
end
If you're doing this a lot, you could use a before filter:
class DemoController < ApplicationController
before_filter :set_instance_array
def index
...
end
...
end
This would call the set_instance_array method before every request. See http://guides.rubyonrails.org/action_controller_overview.html#filters for more info.
Upvotes: 0