Akash
Akash

Reputation: 5221

Instance variable in controllers

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

Answers (2)

Jason Noble
Jason Noble

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

Baldrick
Baldrick

Reputation: 24340

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

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

Upvotes: 4

Related Questions