Commit aaa3f2bd authored by John Noel's avatar John Noel

Optimization #2 - Controller Callbacks

parent 8c65cdc8
class PostsController < ApplicationController
before_action :set_post, only: [:show, :destroy, :edit, :update]
def index
@posts = Post.all
end
def show
@post = Post.find_by(id: params[:id])
end
def new
......@@ -22,22 +22,14 @@ class PostsController < ApplicationController
end
def destroy
@post = Post.find_by(id: params[:id])
if @post.present?
@post.destroy
alert = "You have successfully deleted a post."
else
alert = "Post not found."
end
redirect_to posts_path, alert: alert
@post.destroy
redirect_to posts_path, alert: "You have successfully deleted a post."
end
def edit
@post = Post.find_by(id: params[:id])
end
def update
@post = Post.find_by(id: params[:id])
if @post.update(post_params)
redirect_to posts_path, notice: "You have successfully updated a post."
else
......@@ -49,4 +41,9 @@ class PostsController < ApplicationController
def post_params
params.require(:post).permit!
end
def set_post
@post = Post.find_by(id: params[:id])
redirect_to posts_path, alert: "Post not found" if @post.nil?
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment