S
S
Sergey Fuksman2014-05-02 18:07:10
Ruby on Rails
Sergey Fuksman, 2014-05-02 18:07:10

How to use shared variables in a rails controller?

Hello.
Can you please tell me how to create variables that can be used (read and changed) from any Ruby on Rails controller method? Something like this is needed:

class ExController < ApplicationController
  def common_variable
     @com_var = 1
  end

  def first_action
     puts @com_var
  end 

  def second_action
     @com_var = 2
  end
end

What I expect:
first_action
>> 1
second_action
first_action
>> 2

What is actually happening:
first_action
>> nil
second_action
first_action
>> nil

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Fuksman, 2014-05-02
@fuksman

To store data common to all controller methods, you should use the session mechanism:
guides.rubyonrails.org/action_controller_overview....

V
Viktor Vsk, 2014-05-02
@viktorvsk

@var - class instance variable
@ @var - class variable
$var - global variable

A
Arkady Butermanov, 2014-05-02
@Arkadey

Did you answer your own question?) Specify the question, please)

I
Ivan Kryak, 2014-05-02
@sck_v

If you need to save the value of a variable between requests, then cookies or session.
Describe the problem more clearly. I'm sure there is a more elegant solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question