3

Title says it all. It's pretty easy from controllers - just using "view_context". But it doesn't work with models.

E.g ApplicationController.new.view_context.url_for yields in: "undefined method 'host' for nil:NilClass"

ActionView::Base.new(Rails.configuration.paths["app/views"].first).url_for doesn't work as well.

Can this be done without so much pain ?

P.S I need it for my Prawn gem! I wanted to generate the PDF from the model. And apart from generating the links inside of it - it is very successful!

Hope for your help! Thanks in advance!

Veger
  • 37,240
  • 11
  • 105
  • 116
Dmitri
  • 2,451
  • 6
  • 35
  • 55

2 Answers2

4

Rails 5

include Rails.application.routes.url_helpers

url_for(myModelObject)
Confused Vorlon
  • 9,659
  • 3
  • 46
  • 49
2

It might depend on Rails version, but generally this method is now defined in Rails.application.routes. It expects you to provide hash with url_options, with :host key among others.

samuil
  • 5,001
  • 1
  • 37
  • 44