Ruby on Rails Controller Code Sample

Mav Tipi
3 min readOct 8, 2020

When I’m beginning to learn a new technology, the thing I most frequently can’t find is a code sample. I’m always looking, just to see the full syntax, how everything fits together. Previously I’ve gone through code samples for React components (Part I and II) and mouse events, and Rails finder methods. This post will be a rundown of a code sample for a typical Rails controller.

What’s the controller again?

The controller is a third of the MVC pattern, key to a Rails application. It’s responsible for the actions a user can perform on the model.

image from wikimedia

If you’re here you know that, but maybe it’s good to have a reference. That’s the point of this whole post.

Note that the user actually manipulates elements of the view, which communicates with the controller.

The titular code sample

sorry, you can’t copy-paste it :P

This is a controller for the resource Catalogs. Each resource gets its own model file, its own controller file, and its own view file. We can see from the “create” method that “Catalogs” belong to “Sellers”; this might be some kind of ecommerce platform, or something in that area.

You’ll notice that we’re basically implementing CRUD: Our user can create, show (read), update, and destroy catalogs. The index returns all the catalogs.

A controller would also be responsible for validating that the user is authorized to perform these actions, if that’s something you wanted. That’s not present in our sample.

Let’s take a look at some of the elements of the controller.

If you’ve created your resource with rails g controller or rails g resource, it’ll create this file for you, and put it right here; if not, you’ll have to make it yourself. The naming convention (plural_controller.rb) is significant; you may have already realized that Rails fully runs on naming conventions.

This, too, is automatic when you rails g the controller. Everything else, you have to fill out yourself. Once again, if you’re doing it yourself, make sure you follow the pattern: capitalized, plural, no underscore. Deviating from the pattern will cause small or large issues; for example, if we named it CatalogController instead, it would work, but your routes would need a higher degree of specificity to function. Rails’ naming conventions allow files to find each other and know each others’ functions.

You can see that CatalogController is inheriting from ApplicationController; what this means is that if you have methods that you want to be available to all your controllers, you can lift them up to the ApplicationController.rb file. ApplicationController in turn inherits from ActionController, from whence it gets its powers.

In the next installment we’ll talk about those RESTful methods inside the controller, and add some authorization checks.

--

--