简体   繁体   中英

Wrong url in the link_to helper

When I use link_to in rails

I know that the form is

link_to "Profile", profile_path(@profile)
# => <a href="/profiles/1">Profile</a>

but in my code

<% @posts.each do |post|%>
  <h2><%=post.title %></h2>
  <p><%= post.content%></p>
  <%=link_to "show", posts_path(post.id) %>
<%end%>

I expect my url looks like posts/1 but it was posts.1

Try <%=link_to "show", post_path(post) %>

post not posts . See here http://guides.rubyonrails.org/routing.html

link_to comes with syntax/signature link_to(name = nil, options = nil, html_options = nil, &block) Which creates a link tag of the given name using a URL created by the set of options.

Signatures;

link_to(body, url, html_options = {})
  # url is a String; you can use URL helpers like
  # posts_path

link_to(body, url_options = {}, html_options = {})
  # url_options, except :method, is passed to url_for

link_to(options = {}, html_options = {}) do
  # name
end

link_to(url, html_options = {}) do
  # name
end

I will take the same example from your question,

This link_to "Profile", profile_path(@profile) creates path;

# => <a href="/profiles/1">Profile</a>

whereas, <%=link_to "show", posts_path(post.id) %> creates

# => <a href="/profiles.1">show</a>

Other options to create appropriate routes are as follows;

link_to "Profile", @profile
# => <a href="/profiles/1">Profile</a>

link_to "Profile", controller: "profiles", action: "show", id: @profile
# => <a href="/profiles/show/1">Profile</a>

Hope this could help you otherwise see this link_to apidoc

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