3

In my Rails 5 app, I'm trying to get the full URL for my instance, but when I tried to use url_for as suggested in this SO question, I get an error, NoMethodError: undefined method 'url_for' for #<Product:0x8646fc0>.

Full URL with url_for in Rails

def get_url
  url = url_for(self)
end

I also tried product_url(self) and received a similar error.

What's the proper way to get the URL for my instance? Thanks!

Community
  • 1
  • 1
yellowreign
  • 3,528
  • 8
  • 43
  • 80

1 Answers1

4

helper method is only available in view or decorator. it's better to define url in the decorator.

if you want to use helper method in the model, try this

def url
  Rails.application.routes.url_helpers.product_url(self)
end
Dorian
  • 7,749
  • 4
  • 38
  • 57
silentfox
  • 129
  • 3
  • 1
    I got this to work, but had to add the host and only_path options for it to show the complete url `Rails.application.routes.url_helpers.product_url(self, :only_path => false, :host => "www.foo.com")` – yellowreign Mar 03 '17 at 07:31
  • 1
    you can specify protocal too. like this `Rails.application.routes.url_helpers.product_url(self, :host => "www.foo.com", :protocal => 'https')` – silentfox Mar 03 '17 at 09:21
  • Would this work for development too or just for production? – Beulah Akindele Mar 13 '20 at 09:48