Skip to content

Commit 1871362

Browse files
author
Ryan Bigg
committed
Section 4.4.2: Redirect the users back to the projects page if they try going to a project that does not exist
1 parent 525f0b0 commit 1871362

File tree

2 files changed

+20
-11
lines changed

2 files changed

+20
-11
lines changed

ticketee/app/controllers/projects_controller.rb

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
class ProjectsController < ApplicationController
2+
before_action :set_project, only: [:show,
3+
:edit,
4+
:update,
5+
:destroy]
26
def index
37
@projects = Project.all
48
end
@@ -19,17 +23,7 @@ def create
1923
end
2024
end
2125

22-
def show
23-
@project = Project.find(params[:id])
24-
end
25-
26-
def edit
27-
@project = Project.find(params[:id])
28-
end
29-
3026
def update
31-
@project = Project.find(params[:id])
32-
3327
if @project.update(project_params)
3428
flash[:notice] = "Project has been updated."
3529
redirect_to @project
@@ -40,7 +34,6 @@ def update
4034
end
4135

4236
def destroy
43-
@project = Project.find(params[:id])
4437
@project.destroy
4538

4639
flash[:notice] = "Project has been destroyed."
@@ -50,6 +43,15 @@ def destroy
5043

5144
private
5245

46+
def set_project
47+
@project = Project.find(params[:id])
48+
rescue ActiveRecord::RecordNotFound
49+
flash[:alert] = "The project you were looking" +
50+
" for could not be found."
51+
52+
redirect_to projects_path
53+
end
54+
5355
def project_params
5456
params.require(:project).permit(:name, :description)
5557
end
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
require 'rails_helper'
22

33
RSpec.describe ProjectsController, :type => :controller do
4+
it "displays an error for a missing project" do
5+
get :show, id: "not-here"
46

7+
expect(response).to redirect_to(projects_path)
8+
message = "The project you were looking for could not be found."
9+
10+
expect(flash[:alert]).to eql(message)
11+
end
512
end

0 commit comments

Comments
 (0)