In my Rails 4 application I have a model that needs to build links to other parts of the application. I am using Rails.application.routes.url_helpers.<path_name>
to generate the URL of this link. The problem I have is that this generated path doesn't included the nested path.
Locally the app is served to localhost:3000
and all the paths work correctly, but when I deploy to a remote server it is served by Nginx/Passenger using the root http://<servername>/admin
and the paths are incorrect. So as an example, what I want is payments_path
to resolve to "/admin/payments"
, but instead I get "/payments"
.
The strange thing is when I use payments_path
directly in my view or other places in my app, I get the path with the nested /admin
path, ie "/admin/payments"
.
Anyone have any idea why path is giving me two different things in the view and the Rails.application.routes.url_helpers
?
I think the core issue is that path generation at the view / controller level is getting some additional metadata to generate the paths correctly. I ended up finding a blog post dealing with the subject of routes inside models.
The author of the blog (Adam Hawkins) recommends the following approach for adding paths generation as a concern to the model,
module Routing
extend ActiveSupport::Concern
include Rails.application.routes.url_helpers
included do
def default_url_options
ActionMailer::Base.default_url_options
end
end
end
class UrlGenerator
include Routing
end
This concern piggybacks off the ActionMailer configuration, which in my case is,
config.action_mailer.default_url_options = { host: 'https://dev.<domain-name>.com/admin' }
However after I added this concern I still couldn't generate the full relative path, but I could get the absolute url generation working. So I ended up using payments_url
instead of payments_path
.
I think there is probably a way to get relative paths to work, but this is my workaround for the time being.