Adjusting the Pages


Collapse Content

Adjusting Routes

Let's change make the posts index page the home page. Add the following line to routes.rb:

  root to: 'posts#index'

Now let's remove the default index route from the posts resources:

  resources :posts, except: :index

Visitors to that page can be redirected to the root page:

  get '/posts' => redirect('/')

Here's the whole routes file:

config/routes.rb

Rails.application.routes.draw do    
  resources :posts, except: :index
  get '/posts' => redirect('/')
  root to: 'posts#index'

  devise_for :users
  resources :users    
end

Partial Post

Partials make it easy to re-use code in view templates. Can you create a _post partial and use it in the posts index page?


Here's a simple partial that just displays the content of a post:

app/views/posts/_post.html.erb

<%= post.content %>

Add some more HTML and Ruby to display more information with each post:

<div class="post">
  <p><%= post.content %></p>
  <small><%= link_to post.created_at.strftime("%a %m:%M%p"), post %></small>
</div>

You can now shorten the main part of the posts/index page to one line:

app/views/posts/index.html.erb

<h1>All Posts</h1>    
<%= render @posts %>      
<br>

<% if user_signed_in? %>
  <%= link_to 'New Post', new_post_path %>
<% end %>

Next, can you modify the user show page to display all the posts of the user?

User Posts

Show Post

Now that we've edited how a posts is displayed in a list, let's adjust how it looks on its own page:

app/views/posts/show.html.erb

<div class="one-post">
  <div>
    <%= simple_format @post.content %>        # 1
  </div>
  <small><%= link_to @post.user.name, @post.user %></small> # 2

<% if correct_user?(@post) %>
    <%= link_to 'Edit', edit_post_path(@post) %>
    <%= link_to 'Destroy', @post, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
</div>
  1. This code uses the Rails method simple_format to display the post's newlines (as <br> or <p>).
  2. Afterwards, there's a small link to the user's show page, so people can view other posts by that user.
Contact Us
Sign in or email us at [email protected]