【问题标题】:Wrong url in the link_to helperlink_to 帮助程序中的错误 url
【发布时间】:2017-05-06 06:04:02
【问题描述】:

当我在 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

【问题讨论】:

  • 你可以试试&lt;%=link_to "show", posts_path(post) %&gt;
  • 对不起它不起作用:-(
  • 能否分享你的routes.rb文件,你需要在你的html文件中添加post_path(post)

标签: ruby-on-rails ruby link-to


【解决方案1】:

link_to 带有语法/签名link_to(name = nil, options = nil, html_options = nil, &amp;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>

&lt;%=link_to "show", posts_path(post.id) %&gt; 创建

# => <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

【讨论】:

    【解决方案2】:

    试试&lt;%=link_to "show", post_path(post) %&gt;

    post 不是posts。看这里http://guides.rubyonrails.org/routing.html

    【讨论】:

    • 如果你能描述问题和你的答案,那就太好了,以收集更多的赞成票。
    猜你喜欢
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2014-05-13
    • 2015-01-06
    相关资源
    最近更新 更多