- Intro to Fast Rails Development
- Rails Quick Start
- Rails Scaffold
- Scaffold Tour I - Resources
- Scaffold II - Forms
- User Post Relationship
- Validations & Filters
- Correct User
- Adjusting the Pages
- Header Adjustments
- Simple Twist
- 1000 Words
- Live Site on Heroku
Build a quick blog platform with Rails. (Beta tutorial.)
Adjusting the Pages
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?
First, assign @posts in the users show action:
app/controllers/users_controller.rb
def show
@user = User.find(params[:id])
@posts = current_user.posts
end
Next, render them in the view:
app/views/users/show.html.erb
<h2><%= @user.name %>'s Posts</h2>
<%= render @posts %>
(You can also modify the content of the page while you're at it.)
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>
- This code uses the Rails method simple_format to display the post's newlines (as
<br>
or<p>
). - Afterwards, there's a small link to the user's show page, so people can view other posts by that user.