Following on from part 3 we are now going to add the functionality to edit and delete the articles in our app, Within the article controller file I have added the following code continuing with the principles of CRUD (create, read, update, destroy). Being we are now added functionality to edit articles we are are in the update portion of CRUD.
As you probably guessed by now we again need to add a new view, this time for the edit page, remember we need to create this with a corresponding name ‘edit’. In the article views I created the file edit.html.erb.
As you may of notice from looking at this form its incredibly similar to the one we made previously for the creating articles view. The reason for this is we want the same fields however, this time we are retrieving the existing data of an article, we have the same validation as we still want the same restrictions when resubmitting. We retrieve the selected article from the edit method in the article controller and pass it to the page with its existing fields. Being this is repetitive code we can use what's called a partial to dry up our code.
I created a new file in the article views and called it _form.html.erb, and moved all the code within the form_with code block here. I then called the form to be rendered in the edit articles view and the new articles view in the following way.
Now this all updated we need to create the update method, so returning to our article controller we add the following code. Once again as mentioned before Rails follows the concept of CRUD (create, read, update destroy), this method will instruct rails to update the article provided it meets our validation criteria.
Now we have added all the logic we just need to add a link to the edit view, in the article form located in out index I added the following.
<td><%= link_to ‘Edit’, edit_article_path(article) %></td>
Now if we run our rails server we should be provided an edit link next to each article we add to our list.
Ok let's destroy some stuff!
Returning back to our article controller we add the final part of CRUD, ‘destroy’, as you would guess this will be used to remove the articles.
Finally, we add this method to are articles index, this is what the index form currently looks likes, take a look at the code.
Part 5 will be added shortly, thanks for reading!