1

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.

6
  • this code is definitely not Ruby, how do we know where you're getting into trouble? Commented Mar 11, 2012 at 15:18
  • 1
    @NashBridges syntactically Newton's code is valid Ruby code. Why do you think it is not? Commented Mar 11, 2012 at 17:23
  • @KandadaBoggu well... even after editing it's still...Python :) Commented Mar 11, 2012 at 17:42
  • The method naming conventions certainly indicates non Ruby native tongue(may be Java?). But the code will still compile and run. Commented Mar 11, 2012 at 17:48
  • 1
    In Ruby most of the developers use snake case. Apart from that, one typically uses attr_accessor(rubyist.net/~slagell/ruby/accessors.html) instead of explicit getters and setters. Commented Mar 12, 2012 at 1:00

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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.