开发者

How link_to mechanism works in Ruby on Rails

开发者 https://www.devze.com 2023-03-24 03:58 出处:网络
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:

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><%= lin开发者_如何学Ck_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>

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.

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 ?


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

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

    class PostsController < ApplicationController
      ...
      def index2
      end
      ...
    end
    
  2. Create a view file for it in the app/views directory called index2.html.erb

  3. Add a route to config/routes.rb, for example:

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

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

I highly recommend the book Agile Web Development with Rails (Pragmatic Programmers)


Not sure what exactly you mean by writing link_to and corresponding code in post_controller.rb

The link_to mechanism can be simplified like this:

link_to('whatever you want to display in the link',{:controller => 'corresponding controller name',:action => 'corresponding action name'})

As far as rendering a different template is concerned simply go the controller and write this:

render('controllername/view')

Hope this will help

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号