link_to 机制如何在 Ruby on Rails 中工作 [英] How link_to mechanism works in Ruby on Rails

查看:44
本文介绍了link_to 机制如何在 Ruby on Rails 中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照给定的说明实施了官方创建博客应用程序项目.但我不明白在这个项目中使用 link_to 的想法:

I implemented the official Creating the Blog Application project as per the directions given. But I am not getting the idea of link_to used in this project like:

<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中也有相应的代码,用于在app/views/posts/ 目录.

given in app/views/posts/index.html.erb file, also corresponding code in app/controllers/posts_controller.rb for rendering html pages in app/views/posts/ directory.

如果我想呈现一个新的 html 页面,请在没有编辑"和销毁"的 app/views/posts/ 目录中说 index2.html.erb'链接与index.html.erb相比,那link_toposts_controller.rb中对应的代码应该怎么写?

If I want to render a new html page say index2.html.erb in app/views/posts/ directory that does not have 'Edit' and 'Destroy' links compared to index.html.erb, then how should I write link_to and corresponding code in posts_controller.rb ?

推荐答案

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

If you want an action called index2, say for a example URL like http://localhost:3000/posts/index2, then you need to:

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

  1. Create an action (method) for it in the posts_controller.rb:

class PostsController < ApplicationController
  ...
  def index2
  end
  ...
end

  • app/views 目录中为它创建一个名为 index2.html.erb

  • Create a view file for it in the app/views directory called index2.html.erb

    添加路由到config/routes.rb,例如:

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

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

    To link to the newly created index2 page, add a link in some other html.erb file to it like this:

    link_to "index 2",index2_post_path
    

    我强烈推荐Agile Web Development with Rails (务实的程序员)

    这篇关于link_to 机制如何在 Ruby on Rails 中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆