使用 Ruby on Rails 创建链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2121281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating Link with Ruby on Rails
提问by scarysnow
Obviously, I am new to this.
显然,我对此很陌生。
I need to make a link using rails to something within the model. The code I have is this. It is probably not even the correct syntax:
我需要使用 rails 链接到模型中的某些内容。我的代码是这样的。它甚至可能不是正确的语法:
<li id="nav_home"><%= link_to 'SOMETHING', {:controller => 'inventories', :action => 'home'} %></li>
This code defaults to creating a text link, but I want the link element to link. Ideally it would output as so:
此代码默认创建文本链接,但我希望链接元素进行链接。理想情况下,它会输出如下:
<li><a href="goes-to-something"></a></li>
Thanks!
谢谢!
回答by Ben
The whole point of link_tois that it helps you create links to resources within your application via your routes. If all you want is <li><a href="#"></a></li>, then just use <li><a href="#"></a></li>--- no need to involve link_to.
重点link_to是它可以帮助您通过路由创建到应用程序中资源的链接。如果您想要的只是<li><a href="#"></a></li>,那么只需使用<li><a href="#"></a></li>--- 无需涉及 link_to。
回答by Alex Wayne
<li><%= link_to '', '#' %></li>
But that's a bit nutty. Plain HTML is fine. Or there is link_to_functionwhich will create a link like that but have an onclickthat executes some javascript.
但这有点疯狂。纯 HTML 没问题。或者有link_to_function哪个会创建一个这样的链接但是有一个onclick执行一些javascript的链接。
Or you can call other helpers in place of your "SOMETHING"
或者你可以打电话给其他帮手代替你的 "SOMETHING"
<li><%= link_to image_tag('foo.png'), '#' %></li>
Renders:
渲染:
<li><a href="#"><img src="/images/foo.png"/></a></li>
回答by Toby Hede
If you are using JavaScript to make this empty link do something, you don't actually need a link - you can place an event on any HTML element and handle if accordingly.
如果您使用 JavaScript 使这个空链接做某事,您实际上并不需要链接 - 您可以在任何 HTML 元素上放置一个事件并进行相应处理。
回答by Paul Fedory
I think you want to look at Rail's RESTful named routes, which provide the various "inventories_path" and "inventories_url" functions. If, in your routes.rb, you have "map.resources :inventories" then you get all these functions for free.
我想你想看看 Rail 的 RESTful 命名路由,它提供了各种“inventories_path”和“inventories_url”函数。如果在您的 routes.rb 中,您有“map.resources :inventories”,那么您可以免费获得所有这些功能。
Check out the Rails Guide on Routing. Then you can do something like:
查看Rails Guide on Routing。然后你可以做这样的事情:
link_to "SOMETHING", inventory_url(@myinventory)

