I use polimorphic_path and it some buggy. This method require some route helper that not defined. How can I define (like regular method) own route helper which will be used like "model_name_path, model_name_url etc"?
Asked
Active
Viewed 2,044 times
2 Answers
4
This solution worked for me.
Add this code to the end of config/routes.rb
file. Make sure to replace MyApp
with your application's name.
MyApp::Application.routes.named_routes.module.module_eval do
def model_name_path(*args)
# Your code here
end
def model_name_url(*args)
# Your code here
end
end
MyApp::Application.routes.named_routes.instance_eval do
@helpers += [:model_name_path, :model_name_url]
end
These custom methods will be available in controllers, views and tests.

Anton Styagun
- 1,112
- 14
- 10
-
1in Rails 4: Rails.application.routes.named_routes.url_helpers_module.module_eval do ... – luckyjazzbo Jun 16 '15 at 12:00
2
I know one possible answer for _path, but the same isn't working for me for _url. Anybody know why?
# at the bottom of config/routes.rb
module ActionView::Helpers::UrlHelper
def model_name_path model, args={}
# your implementation
end
end

Ben
- 173
- 1
- 14
-
Oh, I think it does work for _url too, just that I was calling the _url from a controller and not a view. – Ben Jan 27 '12 at 02:17
-
Say I have a helper method name called user_links, where do I specify the method name as per your e.g., . I have a Post model. My code, looks like this:- ~ module ActionView::Helpers::UrlHelper def post_name_path post, args={} # your implementation --> what exactly should this have ? end end ~ – boddhisattva Jan 02 '13 at 04:09
-
I'm sorry, I tried using an appropriate code block but somehow couldn't get it right in the comments section. – boddhisattva Jan 02 '13 at 04:15