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
2010-03-01 07:52:48
attr_accessor means that I can access this variable all over the class instance. Hmm.. I'll try this! Thanks!
Antiarchitect
2010-03-01 09:16:42
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
2010-03-01 13:50:03
Set the value in a `before_filter`
KandadaBoggu
2010-03-01 17:34:18
I have updated the answer, check to see if it works for you.
KandadaBoggu
2010-03-01 17:41:49
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
2010-03-02 00:49:43
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
2010-03-02 01:25:42
At last it works. It works only with config.cache_classes = true.
Antiarchitect
2010-03-02 06:01:35
Yes, it makes sense. Rails reloads the classes for every request in `development` mode.
KandadaBoggu
2010-03-02 06:17:17
A:
you can use rails cache.
Rails.cache.write("list",[1,2,3])
Rails.cache.read("list")
allenwei
2010-03-01 09:38:59
Your way seems to be working! I didn't found a good docs for Rails.cache can you provide me a link please.
Antiarchitect
2010-03-01 14:10:02
I second `Tony`. Unless you ensure the uniqueness of the `list` name across the session this solution will fail during concurrent requests.
KandadaBoggu
2010-03-01 17:33:32