Antiarchitect
Antiarchitect

Reputation: 1952

How to pass values between controller methods

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.

Upvotes: 7

Views: 16687

Answers (3)

Milind
Milind

Reputation: 5112

I am not sure whether my answer is close to your requirement, but this is what I do if I want to get the value of an object/model which is fetched in one controller action and basis on that value I need to fetch other values in another controller action. I make use of class variables and use it throughout my controller action

for eg:

@pages=Post.find.all`

@@my_value=@pages.(any manipulations)

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

hope it helps...

Upvotes: 3

Harish Shetty
Harish Shetty

Reputation: 64363

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.

Upvotes: 5

allenwei
allenwei

Reputation: 4137

you can use rails cache.

Rails.cache.write("list",[1,2,3])
Rails.cache.read("list")

Upvotes: 6

Related Questions