簡體   English   中英

link_to幫助程序中的URL錯誤

[英]Wrong url in the link_to helper

當我在rails中使用link_to

我知道表格是

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

但是在我的代碼中

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

我希望我的網址看起來像posts/1但它是posts.1

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

post不是posts 看到這里http://guides.rubyonrails.org/routing.html

link_to帶有語法/簽名link_to(name = nil, options = nil, html_options = nil, &block)使用由選項集創建的URL創建給定名稱的鏈接標記。

簽名;

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

我將從你的問題中拿出同樣的例子,

link_to "Profile", profile_path(@profile)創建路徑;

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

<%=link_to "show", posts_path(post.id) %>創建

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

創建適當路線的其他選項如下:

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>

希望這可以幫助您另外看到此link_to apidoc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM