0

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.