Index View in Ruby

Jr Medina
3 min readMay 10, 2021

I have recently been doing some contract work for a startup, and have been working in ruby on rails for the back end. I learned a bit about this framework through the Bootcamp I completed and am now realizing how far I have come, and how much I still have to learn.

One of the things I have learned is how to incorporate the portion of the view on the MVC model. There may be many ways to do this but the way I have learned this skill is by using the jbuilder gem found in a rails gem file. This needs to be commented back in and a bundle install command needs to be executed in order to use this.

Next, a model and a controller will have to be created. In my example, I have created a Bank model that has a name and a location as attributes. Along with this, I created a controller with an index method shown below.

In my program, we were taught to include a “render json : @banks” in our index method to show them all. What I found is that rails are built to pass this job off to the views in rails to do the heavy lifting. It automatically checks views for the correct files to render the endpoint that is hit.

Next, I created a banks folder inside of my views folder, and in my banks' folder I created a file labeled ‘index.json.jbuilder”; this file path looks like this. (app/views/banks/index.json.jbuilder). The contents of this file can be seen below.

I am still sorting through how to read this file, but what it is doing is making the request and looking in the partials folder (that will be created next) to render the bank attributes in json format.

Now I create a partials folder with a file labeled “_bank.json.jbuilder”, the file path looks like this (app/views/partials/_bank.json.jbuilder). The contents of this file will be what is rendered when requested, and the file will have all the attributes linked to my banks. This file is setting my model id, name, and location to json format, and also seeing that bank.id, bank.name, and bank.location is how to pull the requested information.

This does get a bit more complex for a show, but an index and show is all I have needed as of now to be able to render full CRUD actions in a rails back end. I plan on learning more about this and diving further into rails as I have only scratched the surface of this framework.

--

--

Jr Medina

Soon-to-be Flatiron School Successor, with an enthusiasm towards Front-End Web Development, lifelong learning, and continuous improvement.