如何在同一控制器中以不同方法使用对象? [英] How can I use an object in different methods within the same controller?
问题描述
我有一个不同方法的控制器。
在第一种方法中, authorize
我实例化了一个我想在另一个方法中重用的对象。问题是两种方法都有不同的视图,并且控制器实例并不保持不变。
I have a controller with different methods.
In the first method, authorize
I instantiate an object which I would like to reuse in another method. The problem is that both methods have different views, and the controller instance does not remain the same.
Hers是我的代码
def authorize
@session ||= get_session
puts @session
@authorize_url = @session.get_authorize_url
end
def list
puts self
@session ||= get_session
@client = DropboxClient.new(@session, ACCESS_TYPE)
metadata = get_meta_data("/")
@files = []
metadata.each do |data|
@files.push data
end
@files
end
$ b b
那么如何重用@session变量呢?
So how can I reuse the @session variable?
Best
Phil
Best Phil
推荐答案
你不,真的。控制器中渲染视图的每个公共方法都意味着是请求的端点。
You don't, really. Each public method in your controller that renders a view is meant to be an endpoint for a request. The request's lifecycle ends there.
要在请求之间保持数据,您应该使用会话。这可能有点更混乱,因为你确实试图在请求之间保持一个名为 @session
的实例变量,但这是他们要的。
To persist data between requests, you should use sessions. This might be a bit more confusing, since you are indeed trying to persist an instance variable called @session
between requests, but that's what they're for.
Rails通过您的控制器中可用的会话
散列来公开会话数据。有关Rails如何处理会话的详细信息,请参见 Rails文档
Rails exposes session data through a session
hash available in your controllers. More information about how Rails handles sessions is available in the Rails Documentation
class YourController < ApplicationController
def authorize
@session ||= get_session
session[:dropbox_session] = @session
end
def list
@client = DropboxClient.new(session[:dropbox_session], ACCESS_TYPE)
end
end
这篇关于如何在同一控制器中以不同方法使用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!