I started by creating two different repositories: one for the frontend and one for the backend. To get started on the backend, I created a new rails project and a passed the “--api” flag, which will automatically set up files that will allow us to use the app as an API. For expediency, I took advantage of Rails’ scaffold generator and began by scaffolding two resources, a garden and a plant, created the attributes I wanted for each one and set up a relationship between them. In this case a garden has many plants and a plant belongs to a garden.
I then created different instances in the seed file for testing purposes.
In order for the api to allow its information to be fetched in the frontend, it is necessary to uncomment the ‘rack-cors’ gem inside of the gemfile, which is available to us thanks to the “--api” flag used while creating the project.
Then, inside config/initializers/cors.rb, we must uncomment the code for the middleware. This is what actually allows the frontend to use the API.
To run the application one must simply type “rails s”. The resources data is then rendered in JSON.
Inside the API.js file there is an API class. The API class has static methods which either return a url from the backend or execute some type of fetch.
In this case, there is one static method for the url that contains all garden objects(API_DATABASE_URL) and one for the url that pertains to all plant objects(PLANT_DATABASE_URL).
The static methods used to execute fetches are imperative as they are what allows the frontend to communicate with the frontend.
This is possible because we are using the map method to iterate though the array of objects received from the fetches.In each iteration, a new instance of an object is created. Upon the creation of an object(Garden or Plant), there is a rendered method that is called within the constructor. By calling these rendered methods inside the constructor, we are making sure that an object appends upon its creation;
These methods(renderGarden and renderPlant) work very similarly, and their purpose is to append an object to its respective place in the DOM.
The different types of fetches needed to make changes on the DOM are triggered via different event-listeners. This allows us to manipulate the backend and the frontend, assuring that objects on both sides are created, read, updated and/or deleted in conjunction with each other.
Feel free to check out my repo on Github.