ruby-on-rails - link_to 如何在 Rails 中工作?

标签 ruby-on-rails ruby hyperlink

我是 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/

相关文章:

ruby-on-rails - 在为 rspec 测试禁用回调后,如何重新启用回调?

ruby-on-rails - 使用我的排行榜。可以最大限度地减少工作量

ruby - 思维狮身人面像未知类型 'mysql';跳绳

java - java程序可以用Cucumber测试吗?

Ruby 检查数组,返回索引,哪些数据存在

javascript - 滚动到位置的链接

html - 如何从 <td> 表格单元格建立链接

ruby-on-rails - Ruby:向简单的控制台测验应用程序添加计时器

php - 安全页面上的 Symfony 链接

html - simple_form 嵌套 json 属性