我是 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 助手
创建一个足智多谋的路由还将向应用程序中的 Controller 公开一些助手。
对于资源:照片:
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),它返回以当前主机、端口和路径前缀为前缀的相同路径。
最佳答案
你有一个语法错误。这:
<%= 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 文件中定义。
关于ruby-on-rails - link_to 如何在 Rails 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456594/