ruby-on-rails - Ruby on Rails 中的 link_to 机制如何工作

标签 ruby-on-rails

我实现了官方的Creating the Blog Application按照给定的指示进行项目。但我不明白在这个项目中使用 link_to 的想法,例如:

<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>

app/views/posts/index.html.erb文件中给出,在app/controllers/posts_controller.rb中也有相应的代码,用于在中渲染html页面>app/views/posts/ 目录。

如果我想渲染一个新的 html 页面,请在 app/views/posts/ 目录中使用 index2.html.erb ,该目录没有“编辑”和“销毁” ' 链接与 index.html.erb 相比,那么我应该如何在 posts_controller.rb 中编写 link_to 以及相应的代码?

最佳答案

如果您想要一个名为 index2 的操作,例如 http://localhost:3000/posts/index2 这样的示例 URL,那么您需要:

  1. posts_controller.rb 中为其创建一个操作(方法):

    class PostsController < ApplicationController
      ...
      def index2
      end
      ...
    end
    
  2. app/views 目录中为其创建一个名为 index2.html.erb

    的 View 文件
  3. 将路由添加到config/routes.rb,例如:

    resources :posts do
      member do
        get 'index2'
      end
    end
    

要链接到新创建的 index2 页面,请在其他 html.erb 文件中添加一个链接,如下所示:

link_to "index 2",index2_post_path

我强烈推荐这本书Agile Web Development with Rails (Pragmatic Programmers)

关于ruby-on-rails - Ruby on Rails 中的 link_to 机制如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6882207/

相关文章:

javascript - 使用 React Router 在 React/Rails 应用程序中进行身份验证后管理重定向到子域

javascript - Nested_form_fields 在验证失败时显示现有的 has_many 嵌套字段

ruby-on-rails - 如何在 Rails 中使用多对多?

ruby-on-rails - ActionMailer 渲染一次,发送多次?

ruby-on-rails - 如何使用线程池写入我的数据库?

ruby-on-rails - 从 Controller 发送。需要帮忙

ruby-on-rails - 停止记录ActionController::RoutingError Rails 3.2

ruby-on-rails - Rails 嵌套属性数组

ruby-on-rails - Ruby rufus 调度程序 gem

mysql - sql自连接和多对多关系