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)
1
-
2For fullest answers, see stackoverflow.com/q/341143/793946– just__mattJan 13, 2013 at 17:21
Add a comment
|
2 Answers
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. May 30, 2012 at 14:05
-
4FYI, if you need to access routes for engines, the equivalent is: MyEngineName::Engine.routes.url_helpers.some_path Jun 7, 2012 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'
– AndrewFeb 18, 2014 at 0:12 -
3
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.
-
1Rails 2 is ActionView::Helpers:UrlHelper and ActionController::UrlWriter– jvaticMar 23, 2011 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]– jvaticMar 23, 2011 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. Mar 24, 2011 at 8: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!– jvaticMar 24, 2011 at 21:19
-
3