Reputation: 15114
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.
Upvotes: 1
Views: 1759
Reputation: 64363
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]
Upvotes: 3
Reputation: 16012
As @nash mentioned this is not Ruby code here.
However if you store data on class level it is only valid for the current process. That means if you run multiple processes like passenger and other web servers data will not be shared between these processes.
Also age sounds to be related to a Person instance instead of the class.
Upvotes: 1