简体   繁体   中英

Using rails link_to with just an ID

I have a page that needs a link to a User page with a given ID. So if the ID is 1234, I want the final href to be /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?

I would encourage you to use named routes if possible (let Rails to the work for you). That is, add a route to your routes file:

resources :users

You can then write your link_to method as:

link_to "User", user_path(@user)

or

link_to "User", user_path(1234)

For the HTML id

<%= link_to "User", {:controller => "user", :action => "show"}, :id => '1234' %>

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

For the path 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.

Why not use the built in url helpers? URL Helpers

This would allow you to pass the user in question as an object as the 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)

<%= link_to "User", user_url( :id => '1234' ) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM