3

I'm using Rails 3 beta 4 and trying to include ActionController::UrlWriter in my model, which is the correct way to go about it as far as i can tell, but i get "Uninitialized Constant ActionController::UrlWriter".

Any idea why that would be? Did it move in rails 3?

midas06
  • 1,991
  • 2
  • 22
  • 43
  • including Controller's parts in your Models is generally wrong – zed_0xff Jun 10 '10 at 05:27
  • I need to be able to generate named_routes in a model related, definately not controller related action. Where else should it go? Lib? – midas06 Jun 10 '10 at 06:01

2 Answers2

3

First I agree with zed. This shouldn't be done in a model. Your models should be unaware of any http url.

I do the same in a resque job. Here's what I do :

include ActionDispatch::Routing::UrlFor
include ActionController::PolymorphicRoutes
include Rails.application.routes.url_helpers
default_url_options[:host] = 'example.com'

Then you can call any usual url generator.

url_for(object)
page_url(object)

It'll create the link on the host defined as default_url_options[:host]

Damien MATHIEU
  • 31,924
  • 13
  • 86
  • 94
  • sorry I did not get it. So where should midas06 have put that code? why do you still include ActionController::PolymorphicRoutes? isn't in ActionController? – serengeti12 May 17 '12 at 14:19
2

Answers to Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models? are pretty good

or see

http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html

http://siddharth-ravichandran.com/2010/11/26/including-url-helpers-in-models/

Basically, you can do something like this in a model:

def url
  Rails.application.routes.url_helpers.download_attachment_path(self)
end

It is worth considering whether this is the right layer, though. In my case it's for file attachments and I want to do attachment.url instead of writing out a helper a lot.

Community
  • 1
  • 1
nruth
  • 1,068
  • 7
  • 22