简体   繁体   中英

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.

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM