How to pass values ​​between controller methods

Is there a way to share an array between controller methods and store it until the page reloads or the method of another controller is called? Some methods must modify the array.

+7
ruby-on-rails
source share
3 answers

If you want to share this value between the methods of the same controller instance, declare the 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 split this value on two controllers with 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 a unique name for the key for common parameters to avoid collision with existing keys.

Another option is to save the shared array in the session declaration, delete it until the final rendering.

+5
source share

you can use cache rails.

 Rails.cache.write("list",[1,2,3]) Rails.cache.read("list") 
+6
source share

I am not sure that my answer is close to your requirement, but this is what I do if I want to get the value of an object / model that is extracted in one controller action and based on this value, which I need to extract other values ​​in another controller action. I use class variables and use it while my controller is in action.

eg:

 @pages=Post.find.all` @@my_value=@pages.(any manipulations) 

now @@my_vales can be used in any actions of this controller.

hope this helps ...

+1
source share

All Articles