The Fat Model Saved my Contacts

Liz Reyes
Fat Models Saved My Contacts
2 min readJun 11, 2018

--

One of the apps I have developed in coding school is a contact book app; we started developing this by creating an api and restful routes… in the blink of an eye we were integrating SQL queries. In brief, this app is comprised by a back end app with the model Contact, and name, last_name, phone_number, and email as attributes; in addition it also has a front end app with all the restful routes.

While developing the app, I started to focus on views of the app; When I started coding on rails, I styled the data by adding logic to the view files. This is exactly what I did when I wanted to display the full name of the contacts instead of name and last name separately. I was able to successfully do this, but it wasn’t long until I noticed how hard to maintain are views and controllers! this is when I learned about the fat model, skinny controller.

Too much logic on the view and controller files break object in to smaller instance variables, it pulls the data apart and makes it HARD to maintain. I will share the steps on how I achieved to display the full_name of all my contacts in my index view by using model methods.

On the back en application on the app/models folder, there is a file with the name of the model I created, in my case the model is Person, I will be creating my full_name model method.

class Person < ApplicationRecord  def full_name
full_name = name, last_name
end
end

Note that the the Person class is inheriting from Application record, this means that rails has already created the attribute reader and writters already of all the attributes, therefore, we can call them by their name without requiring any kind of special code.

trying full_name method on contact1

Rails models allows to “pack” behaviors and functionalities that will be available anywhere in the app; for example, after creating my full_name method, I can call the full_name of any contact on the rails terminal.

In short, it is a rails best practice to leave the logic out of the view and controller, keep this files as simple and easy to read as you can.

Comparison with and without using model methods

--

--