如何在控制器方法之间传递值 [英] How to pass values between controller methods

查看:42
本文介绍了如何在控制器方法之间传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在控制器方法之间共享数组并存储它直到页面重新加载或调用另一个控制器的方法?一些方法应该改变数组.

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.

推荐答案

如果你想在同一个控制器实例的方法之间共享值,那么,声明一个实例变量:

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.

这篇关于如何在控制器方法之间传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆