问题
I have the following helper method in application_controller.rb
:
class ApplicationController < ActionController::Base
def current_tenant
@current_tenant ||= Tenant.find_by(domain: Apartment::Tenant.current)
end
helper_method :current_tenant
end
The tenant table also stores some information that I want to use in the environment configuration like so (this is development.rb
):
Rails.application.configure do
config.paperclip_defaults = {
:s3_credentials => {
:bucket => current_tenant.amazon_s3_bucket,
:access_key_id => current_tenant.amazon_s3_id,
:secret_access_key => current_tenant.amazon_s3_secret
}
}
end
This gives me this error:
NameError: undefined local variable or method 'current_tenant'
Is it possible to define a method which can be used in views AND environment configuration?
回答1:
It can't work - you can't use your helper method defined in controller in other parts, like models or (in this case) configuration. What's more, the code in development.rb
is executed once, when the application starts. But you want current_tenant
to be executed on every request.
BTW defining helper method as a public method of ApplicationController
isn't very safe practice, since this method also becomes an action.
回答2:
You can't, and in this case it doesn't make sense at all. The paperclip defaults are designed to be request-independent, global configuration defaults.
In your case, you must leave the defaults empty and make sure to pass in your controller the proper configurations to the paperclip instance according to the user. This is described in the documentation.
来源:https://stackoverflow.com/questions/30913810/how-to-use-helper-method-in-environment-configuration