I've got a Product
model.
How do I get the url of a pro开发者_如何学Pythonduct in Rails 3, in a controller.
For example (pseudo code):
def foobar
@product = Product.first
puts @product.url
end
Is such a thing possible?
Assuming the Product
model is mapped as :resources in your routes.rb
file:
def foobar
@product = Product.first
url = product_url(@product)
end
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
.
精彩评论