How do I get the path to a resource in the model? I need to store it in the database and would like the same url as you get from resourcename_path(resource)
Asked
Active
Viewed 3.8k times
43
-
2For fullest answers, see http://stackoverflow.com/q/341143/793946 – just__matt Jan 13 '13 at 17:21
2 Answers
86
In Rails 3 and Rails 4 you can use:
Rails.application.routes.url_helpers
e.g.
Rails.application.routes.url_helpers.posts_path
-
1One hour of searching and nobody managed to give me as simple and clear answer as yours. Thanks a lot. – dimitarvp May 30 '12 at 14:05
-
4FYI, if you need to access routes for engines, the equivalent is: MyEngineName::Engine.routes.url_helpers.some_path – Theo Scholiadis Jun 07 '12 at 16:08
-
Save yourself from copying your `:host` option everywhere and set it once in your environment config files: `Rails.application.routes.default_url_options[:host] = 'localhost:3000'` – Andrew Feb 18 '14 at 00:12
-
3
45
In Rails 3, you can include the url helpers in models (though it normally is not the best way of dealing with things):
class MyClass < ActiveRecord::Base
include Rails.application.routes.url_helpers
end
In Rails 2, I think it's include ActionController::UrlWriter
, but I can't remember. Google is your friend.

idlefingers
- 31,659
- 5
- 82
- 68
-
1Rails 2 is ActionView::Helpers:UrlHelper and ActionController::UrlWriter – jvatic Mar 23 '11 at 20:13
-
Your Rails 3 solution generates the following error: RuntimeError: Missing host to link to! Please provide :host parameter or set default_url_options[:host] – jvatic Mar 23 '11 at 20:14
-
@jvatic, If you use _url as opposed to _path, you need to tell it what the host is. In views it can take the current host, but models have no knowledge of that and so need to be told what to use. – idlefingers Mar 24 '11 at 08:33
-
If I have to specify the host I might as well just hard code the url, looks like I've found a way to get around needing it in the model anyways. Thanks for your time! – jvatic Mar 24 '11 at 21:19
-
3
-
@Sadiksha are you referring to the Rails 2 solution? The code above works in Rails 3... Basically you include the module containing the desired helper and define any variables it expects (found either by reading its code or undefined var/method exceptions). – jvatic Aug 17 '11 at 17:16
-
Save yourself from copying your `:host` option everywhere and set it once in your environment config files: `Rails.application.routes.default_url_options[:host] = 'localhost:3000'` – Andrew Feb 18 '14 at 00:11