|
1 | | -# class Task |
2 | | -# def initialize(name) |
3 | | -# @name = name |
4 | | -# @complete = false |
5 | | -# end |
6 | | -# end |
7 | | - |
8 | | -TASKS = [ |
9 | | - {name: 'Buy Jesse a toy', complete: false}, |
10 | | - {name: 'Percy needs flea pills', complete: true}, |
11 | | - {name: 'Reload chantals coffee card', complete: true} |
12 | | -] |
13 | | - |
14 | 1 | class TasksController < ApplicationController |
15 | 2 | def root |
16 | 3 | @message = 'Hello world!' |
17 | 4 | end |
18 | 5 |
|
19 | 6 | def show |
20 | | - @task = Task.find(params['id']) |
| 7 | + # This is the ruby try-catch. |
| 8 | + # If Task.find throws an exception |
| 9 | + # (e.g., can't find a task with that id) |
| 10 | + # then we can catch the exception and |
| 11 | + # redirect the user to the homepage with a message. |
| 12 | + begin |
| 13 | + @task = Task.find(params['id']) |
| 14 | + rescue |
| 15 | + flash[:error] = "Could not find task with id: #{params['id']}" #not printing??? why! |
| 16 | + redirect_to tasks_path |
| 17 | + return |
| 18 | + end |
21 | 19 | end |
22 | 20 |
|
23 | 21 | def index |
24 | 22 | @tasks = Task.all |
25 | | - #@tasks = TASKS |
26 | 23 | end |
| 24 | + |
| 25 | + def create |
| 26 | + unless params.key?(:task) |
| 27 | + @task = Task.new |
| 28 | + else |
| 29 | + @task = Task.new( |
| 30 | + name: params[:task][:name], |
| 31 | + description: params[:task][:description] |
| 32 | + ) |
| 33 | + if @task.save |
| 34 | + new_task = Task.find_by(name: @task.name) |
| 35 | + redirect_to task_path(new_task.id) |
| 36 | + else |
| 37 | + render :new |
| 38 | + end |
| 39 | + end |
| 40 | + end |
| 41 | + |
| 42 | + def edit |
| 43 | + begin |
| 44 | + @task = Task.find(params['id']) |
| 45 | + rescue |
| 46 | + flash[:error] = "Could not find task with id: #{params['id']}" |
| 47 | + redirect_to tasks_path |
| 48 | + return |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + def update |
| 53 | + begin |
| 54 | + @task = Task.find(params[:id]) |
| 55 | + rescue |
| 56 | + flash[:error] = "Could not find task with id: #{params['id']}" |
| 57 | + redirect_to tasks_path |
| 58 | + return |
| 59 | + end |
| 60 | + |
| 61 | + begin |
| 62 | + if params[:task].key?(:completion_date) |
| 63 | + @task.update( |
| 64 | + name: params[:task][:name], |
| 65 | + description: params[:task][:description], |
| 66 | + completion_date: params[:task][:completion_date] |
| 67 | + ) |
| 68 | + else |
| 69 | + @task.update( |
| 70 | + name: params[:task][:name], |
| 71 | + description: params[:task][:description] |
| 72 | + ) |
| 73 | + end |
| 74 | + redirect_to task_path(params[:id]) |
| 75 | + rescue |
| 76 | + render :new |
| 77 | + return |
| 78 | + end |
| 79 | + end |
| 80 | + |
27 | 81 | end |
0 commit comments