Search code examples
ruby-on-railsrubyinstance-variables

Lifecycle of Instance variables in Ruby on Rails


I am not quite clear on the life cycle of instance variables in Ruby on Rails.

  1. I have an instance variable @work_days (into which I fetch and load the list of all working days in a month. The month is selected by the user from a date_select in the UI).

  2. Now I have a Generate Report button which generates an excel report by calling a show method in the controller

  3. Every time the user clicks the Generate Report button (and show method gets called), the value of @work_days seems to be nil and I have to initialize it every time.

Is there a way to avoid this? Why does the value of instance variable become nil every time the controller's method show is called?


Solution

  • Rails controller is instantiated per request. It means that every time you receive a request all instance variables are nil and you need to initialize them.