What I learned from my backend Rails and frontend Javascript project
Starting a coding project can be a bit intimidating at the beginning because you don’t know what you are going to need to implement in your project and get it work. For this project, I decided to create a to-do-list app. My Rails back end associations were: A list has many items, and and item belongs to a list. A list has an attribute of “title” and an item has an attribute of “content”.
Sometimes, simple things in a project can be very time consuming, and I must say that I spent two days trying to figure out how to push things into the items arrays that belonged to a list. Below is a snapshot of the List index route:
As you can see above, I was able to successfully create a form in my Javascript frontend and add a new List title called “Shipping List”, but when it came to adding things to the items array, this is where I got stuck for two days trying to figure out how to create a form for the items portion to add new items. I finally came to realize that this was my issue:
Yes, the routing was the main issue here. I was actually fetching the lists index route and was trying to add the associated items by just using the lists route, but in actuality, I need to be using the items route in order to add new items. The funny thing is that when I worked on my previous Rails project, which involved no Javascript, I knew that each model and its corresponding route has its own CRUD actions, but this was the first time that I came across the data structure in the first image, and I thought to myself, if localhost:3000/api/vs/lists
contains the items
array, then I need to somehow grab the items array in my Javascript frontend just using this URI, but this is wrong. Instead of doing this:
const BASE_URL = "http://localhost:3000/api/v1"fetch(`${BASE_URL}/lists`)
I need to do this in order to add new items to the items array
const BASE_URL = "http://localhost:3000/api/v1"fetch(`${BASE_URL}/items`)
Like I previously mentioned, something so simple can make someone spend an unbelievable amount of time to look for a solution. After I solved this issue, I could finally get my hands on Javascript and do some fetch requests and DOM manipulation, and it was an enjoyable experience creating this to-do-list app!