Wednesday 5 March 2014

Ruby on Rails: How to pass variable between controller actions

 way 1 :  
        Global variable  
        (fail during concurrent requests)  
 way 2:  
        class variable  
        (fail during concurrent requests)  
 way 3 :  
 * Stash the object on the server between requests. The typical way is to save it in the session, since it automatically serializes/deserializes the object for you.  
 * Serialize the object and include it in the form somewhere, and  
 deserialize it from the parameters in the next request.  
 so you can store attributes in the session.  
 def first  
  @item = Item.new(params[:item])  
  session[:item_attributes] = @item.attributes  
 end  
 def second  
  @item = Item.new(session[:item_attributes])  
  @item.attributes = params[:item]  
 end  
 way 4 :  
        The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed to the very next action and then cleared out.  
 def new  
   @test_suite_run = TestSuiteRun.new  
   @tests = Test.find(:all, :conditions => { :test_suite_id => params[:number] })  
   flash[:someval] = params[:number]  
 end  
 def create      
   @test_suite_run = TestSuiteRun.new(params[:test_suite_run])  
   @tests = Test.find(:all, :conditions => { :test_suite_id => flash[:someval] })    
 end  
 way 5:  
 you can use rails cache.  
 Rails.cache.write("list",[1,2,3])  
 Rails.cache.read("list")  
 But what happens when different sessions have different values?  
 Unless you ensure the uniqueness of the list name across the session this solution will fail during concurrent requests  
 way 6:  
 In one action store the value in db table based on the session id and other action can retrieve it from db based on session id.  
 way 7:   
 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  
 way 8:   
 From action sent to view and again from view sent to other actions in controller.  

2 comments: