开发者

How to get url of object in controller

开发者 https://www.devze.com 2023-03-04 14:07 出处:网络
I\'ve got a Product model. How do I get the url of a pro开发者_如何学Pythonduct in Rails 3, in a controller.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消