Question

How to get url of object in controller

I've got a Product model.

How do I get the url of a product in Rails 3, in a controller.

For example (pseudo code):

def foobar
  @product = Product.first
  puts @product.url
end

Is such a thing possible?

 21  16441  21
1 Jan 1970

Solution

 32

Assuming the Product model is mapped as :resources in your routes.rb file:

def foobar
  @product = Product.first
  url = product_url(@product)
end
2011-05-06

Solution

 21

In addition to named route product_url(@product) you can use the general url_for(@product) (docs). This has a side effect that if you have nested or namespaced routes, it is shorter:

customer_product_url(@customer, @product)
url_for([@customer, @product])

Also note, that by default url_for produces relative URLs, just as product_path would, which depending on your needs might be good or bad. To get full URL, pass :only_path => false.

2011-05-06