- 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.)
Correct User
Now that we added filters for signed_in users, we need to set up authorization for the correct user. You don't want every signed_in user to be able to edit any other user's posts!
Controller
First, let's make sure the controller actions are protected, with the following line of code:
class PostsController < ApplicationController
#..
before_action :correct_user, only: [:edit, :update, :destroy]
This will run the method correct_user
before accessing those actions.
Q: What is this method correct_user
?
A: It's a method we will write now. On the bottom of your controller page, create a new method below the keyword private
. This will mark it as a private method only for internal controller usage.
#... controller methods
private
#...
def correct_user
end
end
Now fill in the method so it checks if the current_user is the post's user.
- First, get the post being modified.
- Compare the post's user with the current user
- redirect to another page if they don't match up
def correct_user
post = Post.find(params[:id]) #1
unless post.user == current_user #2
redirect_to root_path, notice: "No access"
end
end
View - Helpers
Now we need to make sure the "Edit" and "Destroy" links only get displayed to the correct user. Remove those links from the index page, since they're not needed there. Let's wrap those links on the posts/show page like we did with the "New Post" link:
views/posts/show.html.erb
<% if correct_user?(@post) %>
<%= link_to 'Edit', edit_post_path(@post) %>
<%= link_to 'Destroy', @post, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
Now we just need to create the method correct_user?
. Methods that are used by views are called helper methods and are placed in helper files. In this case, the method may be used by different parts of the site, so let's place it in the file ApplicationHelper:
app/helpers/application_helper.rb
module ApplicationHelper
def correct_user?(post)
return post.user == current_user
end
end
This method only returns true of the user of the given post is the same as the current_user. You can now check your page from two different accounts to see if the edit links show up correctly.
Your basic blog app is now ready! You should now be able to identify the different parts of the Rails app in the machine below: