CRUD it
Updating an article
Summary
Kelvin Omereshone explains how to implement the Update (U) operation in CRUD for a Sails.js blog application. Before diving into updates, he first fixes an issue where trying to view a non-existent article results in an error instead of a user-friendly 404 page. He demonstrates how to leverage Sails’ built-in not found response type to handle this gracefully.
Next, he sets up the edit functionality:
Adds a route for editing an article (
GET /articles/:id/edit
).Creates the corresponding Sails action (
view-edit
).Builds the edit page (edit.ejs), pre-filling form fields with existing article data.
Then, he implements the update functionality:
Adds a
POST
route (/articles/:id/edit
) for submitting updates.Creates an
update-article
action.Ensures article fields (
title
,body
, andid
) are validated.Uses
updateOne()
to modify the article and redirects to the updated article page.
After fixing minor issues like incorrect route submission, he successfully demonstrates editing an article in Firefox, ensuring the update reflects in the database and UI.
Transcript
Handling a 404 error for non-existent articles
Starts the Sails server and visits
localhost:1337
.Notices an issue when accessing a non-existent article ID.
Uses Sails’ built-in
notFound
response type inview-article.js
:If
article
isundefined
, it throwsnotFound
.This displays a custom 404 page instead of an error.
Shows how to customize the
views/404.ejs
file but decides to keep Sails’ default style.
Setting up the edit page
Stops the server to make changes.
Adds a new route:
GET /articles/:id/edit
inroutes.js
.Generates a new action
view-edit.js
:Captures the article ID from the request.
Fetches the article using
Article.findOne({ id })
.Passes the article data to the edit page.
Creates
views/pages/articles/edit.ejs
:Copies structure from
new.ejs
.Pre-fills form fields (
title
,body
) with article data.Adds a submit button labeled "Update Article."
Adding an edit button
Adds an "Edit" link in
article.ejs
:<a href="/articles/<%= article.id %>/edit">Edit</a>
Clicking "Edit" now takes the user to the edit page.
Implementing article updates
Adds a
POST
route:POST /articles/:id/edit
.Generates the
update-article.js
action:Validates inputs (
title
,body
,id
).Uses
Article.updateOne({ id }).set({ title, body })
to update the article.Redirects to the updated article.
Fixing submission issues
Notices a 404 error when submitting updates.
Finds a wrong form action in
edit.ejs
and corrects it.Tests the update feature:
Modifies an article.
Submits changes.
Verifies the update works correctly.
Full Course
USD