【问题标题】:Rails reverse autolinkRails 反向自动链接
【发布时间】:2013-03-12 21:53:20
【问题描述】:
我的 Rails 应用中有以下代码:
link_to('???',{:controller => 'profile', :action => 'show', :id => id})
我想摆脱'???'并显示动态生成的 URL。我该怎么做?这有点像 autolink gem 所做的,但我希望 Rails 将 URL 选项转换为文本,反之亦然。
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3
【解决方案1】:
link_to(nil,{:controller => 'profile', :action => 'show', :id => id})
来自link_to documentation:
如果将 nil 作为名称传递,则链接本身的值将成为名称
【解决方案2】:
使用url_for() 获取字符串。
url_for({:controller => 'profile', :action => 'show', :id => id)}
在代码中:
url_hash = {:controller => 'profile', :action => 'show', :id => id}
link_to(url_for(url_hash), url_hash)
查看this question 也可以获取主机名:
url_hash = {:controller => 'profile', :action => 'show', :id => id}
link_to("#{request.host_with_port}#{url_for(url_hash)}", url_hash)