【问题标题】:How link_to works in rails?link_to 如何在 Rails 中工作?
【发布时间】:2016-07-27 04:17:17
【问题描述】:

我是 Ruby on Rails 的初学者,并遵循 Michael Hartl 的 Rails 教程。在第 2 章中,我在使用 link_to 的部分中遇到了以下代码。在我们没有明确写任何 URL 的情况下,link_to 如何知道 link_to 指向哪个?

<h1>Listing users</h1>
    <table>
    <tr>
    <th>Name</th>
    <th>Email</th>
    <th></th>
    <th></th>
    <th></th>
    </tr>
    <% @users.each do |user| %>
    <tr>
    <td><%= user.name %></td>
    <td><%= user.email %></td>
    <td><%= link_to 'Show', user %></td>
    <td><%= link_to 'Edit', edit_user_path(user) %></td>
    <td><%= link_to 'Destroy', user, confirm: 'Are you sure?',
    method: :delete %></td>
    </tr>
    <% end %>
    </table>
    <br />
    <%= link_to 'New User', new_user_path %>

谢谢大家。不知何故,我无法发表评论,因为 JavaScript 未能加载。感谢 amalrik maia 提供链接。

解决方案: http://guides.rubyonrails.org/routing.html

2.3 路径和 URL 助手

创建资源丰富的路由还会向应用程序中的控制器公开许多帮助程序。

在资源的情况下:照片:

photos_path 返回 /photos

new_photo_path 返回 /photos/new

edit_photo_path(:id) 返回 /photos/:id/edit(例如,edit_photo_path(10) 返回 /photos/10/edit)

photo_path(:id) 返回 /photos/:id(例如 photo_path(10) 返回 /photos/10)

这些助手中的每一个都有一个相应的 _url 助手(例如 photos_url),它返回以当前主机、端口和路径前缀为前缀的相同路径。

【问题讨论】:

    标签: ruby-on-rails ruby hyperlink


    【解决方案1】:

    您有语法错误。这个:

    <%= link to 'New User', new user path %>
    

    应该是:

    <%= link_to 'New User', new_user_path %>
    

    路径是 rails 的“助手”。从这里开始:http://guides.rubyonrails.org/routing.html

    它们基本上是指向特定 url 的快捷方法。这些 url 在您的 routes.rb 文件中定义。

    【讨论】:

      【解决方案2】:
      <h1>Listing users</h1>
      <table>
      <tr>
      <th>Name</th>
      <th>Email</th>
      <th></th>
      <th></th>
      <th></th>
      </tr>
      <% @users.each do |user| %>
      <tr>
      <td><%= user.name %></td>
      <td><%= user.email %></td>
      <td><%= link_to 'Show', user %></td>
      <td><%= link_to 'Edit', edit_user_path(user) %></td>
      <td><%= link_to 'Destroy', user, confirm: 'Are you sure?',
      method: :delete %></td>
      </tr>
      <% end %>
      </table>
      <br />
      <%= link_to 'New User', new_user_path %>
      

      link_to 对路径或 URL 一无所知。 URL 由 Rails 的路由助手生成,例如:

      • edit_user_path()
      • new_user_path

      要查看完整的路线列表,请转到您的终端并输入:

      bundle exec rake routes
      

      请参阅routing documentation 了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-19
        • 1970-01-01
        • 1970-01-01
        • 2016-02-22
        相关资源
        最近更新 更多