Rails has a lot of big benefits over regular ruby, one of those is the streamlined process of creating the C in your MVC. The C here stands for “controller”, which essentially controls the flow of logic between the V (view) and M (Model). The controller will receive a request from the view and process the data through the model to then be sent back to the view, and no one makes this easier than rails.
For example say you’re making a program for a restaurant and you want the application to keep track of the orders. The first step would be to create a model named Order, followed by this models controller which would be called OrdersController. There’s many things you can customize in the model itself but for today lets say this is your only model and controller. If I was using this application I would like to be able to see all the orders and maybe even just one order. This would mean the user would have a few routes they can hit in order to see these things.
Setting up these routes is incredibly easy. In your routes file all you have to input is (resources :orders, only: [:index, :show]). This activates the routes and sets up your controller to hit the routes for all orders, “index”, and one order, “show”.
From here, in your controller its time to set up the methods index and show. The index method is very simple you call “render json:” which will convert the data into json notation, then call the model “Order” followed by the method “.all”. All together it will look like this:
The show method will look similar with a few changes. Now we want to find a specific order. Each order will generate its own id so the easiest way is to find the id of the order we’re looking for and render that one. The method “find_by” is used for this exact thing, but where to we find the id? Well we know the id is sent in along with the request, and the request is stored in the params, so looking there seems like the best bet. We’ll call Order, then we’ll find_by the id in the params. The Show method should look like this when completed:
And now your user has the ability to look at every order in the database and find a specific order!