To-do-list application -Sinatra project
For my second project, I was required to build a web application focusing on Model-View-Controller ( MVC ) by using CRUD — Create, Read, Update and Delete. I decided to make a to-do-list application because I personally make to-do lists to help plan out my day.
First I used gem Corneal to build a Sinatra skeleton. Then I set up todolist and user model, controllers, and views for the web application. Here is my a directory tree structure of the project.
I’ve learned about CRUD and have implemented it in my code as seen below.
Create
After request get '/todolists/new’
route, we render new.erb
file. Then post request from the form and the current user can create a new instance and redirect to '/todolists/
route.
get '/todolists/new' do
redirect_if_not_logged_in
erb :"todolists/new"
endpost '/todolists' do
redirect_if_not_logged_in
todo = current_user.todolists.build(params)
todo.save
flash[:notice] = "Your list has been created!"
redirect '/todolists'
end
Read
When we request get ‘/todolists'
, we set todolist of the current user into instance variable@todo
and render index.erb.
Then requestget ‘/todolists/:id’
it will find id number and render the show.erb
file.
get '/todolists' do
redirect_if_not_logged_in
@todo = current_user.todolists
erb :"todolists/index"
endget '/todolists/:id' do
redirect_if_not_logged_in
@todo = Todolist.find(params["id"])
erb :"todolists/show"
end
Update
When we request get ‘/todolists/:id/edit'
, we render edit.erb
file to view the page. Then after the user clicks the update button, the form will send a PUT
request which it updates and saves for us.
get '/todolists/:id/edit' do
@todo = Todolist.find(params["id"])
redirect_if_not_authorized
erb :"todolists/edit"
endput '/todolists/:id' do
@todo = Todolist.find(params["id"])
redirect_if_not_authorized
@todo.update(todo: params["todo"], date: params["date"], time: params["time"], description: params["description"])
flash[:notice] = "Your list has been updated!"
redirect "/todolists/#{@todo.id}"
end
Delete
After the user clicks on the delete button in the form, it sends a request to delete the instance that the user choose and redirects user to ‘/todolists’
route.
get '/todolists/:id' do
redirect_if_not_logged_in
@todo = Todolist.find(params["id"])
erb :"todolists/show"
enddelete '/todolists/:id' do
@todo = Todolist.find(params["id"])
redirect_if_not_authorized
@todo.destroy
flash[:alert] ="Your list has been deleted!"
redirect '/todolists'
end
Walkthrough video of To-do-list (Sinatra project)
If you would like to check out my web application code, here is my code.
References