Updating (editing) Posts
Wednesday May 07 2025 • 03:15 AM
For editing posts, I’m using the PATCH
HTTP method, and I’m still playing around with the method in the Sinatra app to make sure it works well.
Here’s what I got so far:
patch '/posts/:id' do
@post = Post.find_by(id: params[:id])
if @post.update(params[:post])
redirect "/posts/#{@post.id}"
else
status 422
erb :'posts/edit'
end
end
I looked over the code on the Rails app from last night to find the hidden input which changes the form’s method from POST to PATCH, so I added the same to the Sinatra form. I also fixed the action in the edit form template (I had left it pointing to the /posts
URL instead of /posts/:id
).
In the new post method, I had used @post.create(params)
and I assumed that would work for updating posts too, but that was wrong.
While looking over the Rails code, I realized the form sets parameters using a nested format, like post[title]
and post[content]
. I updated the ERB template for both forms to follow this convention for the named parameters.
In summary, implementing the UPDATE part of CRUD from “scratch” in Sinatra required me to:
- Create a GET path method and to render the edit template
- Create a PATCH path method for /post/:id to update singular posts by ID
- Update the HTML form and ensure parameters are nested
I also added a paragraph to indicate if and when a blog post has been updated.