Commit aaa3f2bd authored by John Noel's avatar John Noel

Optimization #2 - Controller Callbacks

parent 8c65cdc8
class PostsController < ApplicationController class PostsController < ApplicationController
before_action :set_post, only: [:show, :destroy, :edit, :update]
def index def index
@posts = Post.all @posts = Post.all
end end
def show def show
@post = Post.find_by(id: params[:id])
end end
def new def new
...@@ -22,22 +22,14 @@ class PostsController < ApplicationController ...@@ -22,22 +22,14 @@ class PostsController < ApplicationController
end end
def destroy def destroy
@post = Post.find_by(id: params[:id])
if @post.present?
@post.destroy @post.destroy
alert = "You have successfully deleted a post." redirect_to posts_path, alert: "You have successfully deleted a post."
else
alert = "Post not found."
end
redirect_to posts_path, alert: alert
end end
def edit def edit
@post = Post.find_by(id: params[:id])
end end
def update def update
@post = Post.find_by(id: params[:id])
if @post.update(post_params) if @post.update(post_params)
redirect_to posts_path, notice: "You have successfully updated a post." redirect_to posts_path, notice: "You have successfully updated a post."
else else
...@@ -49,4 +41,9 @@ class PostsController < ApplicationController ...@@ -49,4 +41,9 @@ class PostsController < ApplicationController
def post_params def post_params
params.require(:post).permit! params.require(:post).permit!
end end
def set_post
@post = Post.find_by(id: params[:id])
redirect_to posts_path, alert: "Post not found" if @post.nil?
end
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