如何在控制器中获取对象的url

时间:2011-05-06 07:22:08

标签: ruby-on-rails

我有一个Product型号。

如何在控制器中获取Rails 3中产品的URL。

例如(伪代码):

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

这样的事情可能吗?

2 个答案:

答案 0 :(得分:30)

假设Product模型映射为:routes.rb文件中的资源:

def foobar
  @product = Product.first
  url = product_url(@product)
end

答案 1 :(得分:19)

除了命名路线product_url(@product),您还可以使用常规url_for(@product)docs)。这有副作用,如果你有嵌套或命名空间的路由,它会更短:

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

另请注意,默认情况下url_for会生成相对网址,就像product_path一样,这取决于您的需求可能是好还是坏。要获取完整的网址,请传递:only_path => false