Search code examples
ruby-on-railsclass-instance-variables

Class instance variables in ActiveRecord (Ruby On Rails)


I am trying to store a value in a model class, for example, values of couple of checkboxes.

I figured I could store them in a class instance variable, however, these values are cleared when I a user clicks elsewhere on the screen.

How can I maintain the values of my class instance variables.

For example

class Person < ActiveRecord::Base

   def setAge(age)
      @@age = age

   def getAge
      return @@age

however, looks like @@age is empty after it is being set.


Solution

  • The rails framework reloads the classes in the development mode. Any values set in prior requests to class variable is lost in a new request. If you run your server in the production mode, your code will work.

    What you are trying to do is a bad practice as concurrent requests can overwrite the state and when you spawn multiple instances of your rails server this solution will not work(as mentioned by @iltempo)

    If you are trying to persist the state across two client requests, you are better off using session variables.

    request 1

    session[:age] = params['age']
    

    request 2

    u = User.new
    u.age = session[:age]