1

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?

1 Answer 1

2

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.

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

10 Comments

thanks much for the clarification. Is the same true for class variables as well?
It depends where you set them. In general, they live as long as the class lives (unless they're unset explicitly).
will the controller class live across multiple requests?
yup. it's loaded once and then lives in memory.
To add clarification. The class is loaded once per process and lived until the end of the process. This differs from development obviously. Due to reloading.
|

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.