[英]Using rails link_to with just an ID
I have a page that needs a link to a User page with a given ID. 我有一个页面,需要链接到具有给定ID的用户页面。 So if the ID is 1234, I want the final href to be /user/1234.
因此,如果ID为1234,则我希望最终的href为/ user / 1234。
I tried to use 我尝试使用
link_to "User", {:controller => "user", :action => "show", :id => 1234 }
This gave me the URL 这给了我网址
/assets?action=show&controller=user&id=1234
What should the link_to parameters be? link_to参数应该是什么?
I would encourage you to use named routes if possible (let Rails to the work for you). 如果可能的话,我鼓励您使用命名路由(让Rails为您工作)。 That is, add a route to your routes file:
也就是说,将路由添加到您的路由文件:
resources :users
You can then write your link_to method as: 然后,您可以将link_to方法编写为:
link_to "User", user_path(@user)
or 要么
link_to "User", user_path(1234)
For the HTML id 对于HTML ID
<%= link_to "User", {:controller => "user", :action => "show"}, :id => '1234' %>
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
For the path id 对于路径ID
link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
# => <a href="/profiles/show/1">Profile</a>
This syntax albeit valid, harkens back to the Rails 2 days. 该语法尽管有效,但仍会持续2天回到Rails。
Why not use the built in url helpers? 为什么不使用内置的URL帮助器? URL Helpers
URL助手
This would allow you to pass the user in question as an object as the link_to 这将允许您将有问题的用户作为对象传递为link_to
<%= link_to "User", user_url( user_object ) %>
or if you prefer to be explicit (this will add it as a params option though) 或者,如果您更喜欢明确的话(尽管这会将其添加为params选项)
<%= link_to "User", user_url( :id => '1234' ) %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.