CRUD stands for Create Read Update & Delete. It allows us to create resources in a database, read or 'get' the resource to display, update a resource without overwriting the original resource and delete a specific resource from the database.
There are seven verb + path combinations that are necessary in a basic Sinatra app in order to provide full CRUD functionality. List each of the seven combinations, and explain what each is for.
All resources: get '/resources'
(ex. get '/tasks'
) => gives us a list of all the resources through a index.erb
file that gets interpreted to html.
One resource: get '/resources/:id
(ex. get '/tasks/1
) => gives us the specific resource through a show.erb
file that gets interpreted to html.
Form for new resource: get '/resources/new
(ex. get '/tasks/new'
) => gives us a form to create a new resource through a new.erb
file that gets interpreted to html.
Create new resource: post '/resources'
) => (ex. post '/tasks'
) => creates a new resource then redirects to desired path.
Form to update an existing resource: get '/resources/:id/edit'
=> (ex. get '/tasks/:id/edit'
) => gives us a form to update a new resource through a edit.erb
file that gets interpreted to html.
Update a existing resource: put '/resources/:id'
=> (ex. put '/tasks/:id'
) => updates an existing resource then redirects to desired path.
Delete a existing resource: delete '/resource/:id'
=> (ex. delete '/tasks/:id'
) => deletes an existing resource then redirects to desired path.
Since browsers do not natively support the verbs put (patch)
or delete
we end up sending post
requests to our web app. To override this, Sinatra allows us to create a hidden input like so: <input type="hidden" name="_method" value="put or delete">
to allow us to use the put
and delete
methods in our controller. But before we can do that we have to tell Sinatra to use method override with set method_override: true
.
Explain the difference between value
and name
in this line: <input type='text' name='task[title]' value="<%= @task.title %>"/>
.
The name attribute gives our form input a name that is sent back to our Sinatra app. We can then access that specific value in Sinatra through the params method likes so: params[:task][:title]
. The value attribute is what is displayed to the user in the input field.
params
is a method provided by Sinatra that allows us to access query params (ie /tasks/1 => params[:id]
) and the request body that is sent from forms.
/tasks/1
, the1
would be considered a dynamic parameter from the url, not a query param. In/tasks/1?mykey=myval
, the part after the question mark would be considered a query param.