Topic: Controller class variable

Hi everyone,

I would like to know how to define a class variable into a controller, for the moment, I do this:

def initialize

end then:

def add_search_criteria
    respond_to do |format|

But during the process, i get a message that tells me the variable hasn't been initialized. What did i do wrong ?
(it's probably very stupid i guess)
Thanks for your help.

Re: Controller class variable

Do you want this number to persist and be incremented across all requests, or just requests for that user?

If it's all requests I'd put it in the database somewhere (or something else that can be shared like a file store or memcached); if it's just requests for a particular user I'd make it a session variable. I don't think the controller class is the right place for something like this.

vinnie - rails forum admin

Re: Controller class variable

Yes, you are right, I just used a session variable and it works fine now. Thanks

Re: Controller class variable

But, it does not explain why it wasn't working... I would like to understand, it's like if the @variable had a method-life-limitation (i dont know how to say this in english...), like if i had to initialize it everytime... Is the controller instance recreated every time ?

Re: Controller class variable

Ruby aint C++ smile

@search_index++ #error

this should work
@search_index += 1

Re: Controller class variable

Got me ! wink
Yes, I tried this too, but i always obtain 2...

Re: Controller class variable

What do you mean by "always" -- you got '2' in each request?

under both Mongrel and Webrick on a Windows machine, the class variables ARE isolated by user session. The problem did not manifest itself until the application was deployed to Linux at our hosting site

If you're in development mode all is reloaded each time you make a request. Not in production mode. … pe-is.html

Re: Controller class variable

@search_index is an instance variable, not a class variable, so you should only expect it to be persistent for the length of that request. If you add an extra @ sign you will make a class variable: @@search_index. This will be persistent for the length of the program execution.

However, you should never rely on these types of variables in Ruby on Rails. The primary reason is when you move into production, it is likely you will have multiple ruby processes running at the same time. Each process will have its own class variable, and the process a given user ends up getting is more or less random.

In short, you should always keep global data in some external database/file if you need it to stay persistent across requests.

Railscasts - Free Ruby on Rails Screencasts

Re: Controller class variable

dr_bonzo wrote:

What do you mean by "always" -- you got '2' in each request?

yes the resut is always equal to 2.

Thanks for your answers