如何在一个方法中将实例变量的值获取到同一个控制器中的另一个方法?

时间:2017-04-22 07:55:39

标签: ruby-on-rails

我的控制器中的一个方法如下:

composer dumpauto

现在我正在定义另一种方法,我想访问此def new_equipment_matches_wanted #..........Big chucnk of code of about 7 to 8 lines and then.. @receiver end 实例变量的值。它将有一个单独的模板。

@receiver

我怎样才能做到这一点?或者我应该在第二种方法中编写相同的代码,只是为了访问该变量中的值?

1 个答案:

答案 0 :(得分:2)

实例变量(带@)在所有控制器的方法之间共享。

def new_equipment_matches_wanted
 #..........Big chucnk of code of about 7 to 8 lines and then..
 @receiver
end 
def send_receivers_to_admin
 @receiver.do_something
end 

您可以阅读有关变量here

的更多信息

然而,正如塞尔吉奥所说,

  

“在请求之间传递实例变量是不可能的......   支持不同请求的控制器操作“

然后你必须在两种方法上加载@receiver,你可以使用before_action

class CustomController < ActionController::Base
  before_action :load_receiver, only [:send_receivers_to_admin,:new_equipment_matches_wanted]

def new_equipment_matches_wanted
  @receiver.do_something
end 

def send_receivers_to_admin
 @receiver.do_something
end 

private

def load_receiver
    # Big chucnk of code of about 7 to 8 lines and then..
    @receiver
end