views:

58

answers:

2

Is there any way to share an array between controller methods and store it until page reloads or calling method of another controller? Some methods should change the array.

A: 

If you want to share the value across the methods of a same controller instance then, declare an instance variable:

class BarsController < UsersController

  before_filter :init_foo_list

  def method1
    render :method2
  end 

  def method2
    @foo_list.each do | item|
      # do something
   end
  end

  def init_foo_list
    @foo_list ||= ['Money', 'Animals', 'Ummagumma']
  end

end

If you want to share the value across two controllers withn a session, then:

class BarsController < UsersController

  before_filter :init_foo_list

  def method1
    render :controller => "FoosController", :action => "method2"
  end 

  def init_foo_list
    params[:shared_param__] ||= ['Money', 'Animals', 'Ummagumma']
  end    
end

class FoosController < UsersController

  def method2
    params[:shared_param__].each do | item|
      # do something
   end
  end
end

Give an unique name to the shared parameter key so as to avoid collision with existing keys.

Other option is to store the shared array in the session ad delete it before the final render.

KandadaBoggu
attr_accessor means that I can access this variable all over the class instance. Hmm.. I'll try this! Thanks!
Antiarchitect
First way not working. foo_list is nil in method2But the first method is called before the second.And how can I define foo_list not in methods but on initialize? def initialize self.foo_list = ['Money', 'Animals', 'Ummagumma'] endIn this way or somehow in another way?
Antiarchitect
Set the value in a `before_filter`
KandadaBoggu
I have updated the answer, check to see if it works for you.
KandadaBoggu
Not working. The value of @foo_list lost between actions. I've set initial value in before filter, then I've changed it's value in method1, and in method2 it has the same value as defined in before filter.In before filter I've set: @foo_list ||= [0]Than im my create action: @foo_list << 1In my update_list action it has [0] value.
Antiarchitect
To preserve the value across the sessions declare the variable as class variable instead of instance variable (i,e. `@@foo_list` instead of `@foo_list`)
KandadaBoggu
At last it works. It works only with config.cache_classes = true.
Antiarchitect
Yes, it makes sense. Rails reloads the classes for every request in `development` mode.
KandadaBoggu
A: 

you can use rails cache.

Rails.cache.write("list",[1,2,3])
Rails.cache.read("list")
allenwei
Your way seems to be working! I didn't found a good docs for Rails.cache can you provide me a link please.
Antiarchitect
But what happens when different sessions have different values?
Tony Fontenot
I second `Tony`. Unless you ensure the uniqueness of the `list` name across the session this solution will fail during concurrent requests.
KandadaBoggu