一般来说, abefore_filter
可以解决您的重新实例化问题。如果您想设置一个可用于每个控制器方法的实例变量,请执行以下操作:
class UsersController < ApplicationController
before_filter :get_user
def profile
# @user is accessible here
end
def account
# @user is accessible here
end
private
def get_user
@user = User.find(params[:id])
end
end
您还可以在应用程序控制器中使用 before_filters来设置可在所有控制器中访问的实例变量。 在此处阅读有关过滤器的信息。
至于将 API 密钥存储到会话中,这是可行的,但如果您想要长期访问,您可能希望将 API 密钥写入数据库。结合之前的过滤器,您可以执行以下操作:
class ApplicationController < ActionController::Base
before_filter :setup_heroku
def setup_heroku
if current_user && current_user.heroku_api_key
@heroku = Heroku::API.new(:api_key => current_user.heroku_api_key)
end
end
end