Purpose of Model Files in Rails
In this lesson, we are going to talk about model files and how we can use them in Ruby. As a first step, we need to understand what are model files and what is their purpose in an application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson, we are going to talk about model files and how we can use them in Ruby. As a first step, we need to understand what are model files and what is their purpose in an application.

To explain, model files are the backbone of every application as it contains all the logic. In any well-developed Ruby application, you can find algorithms, custom work, complex background tasks and calls in these model files. The reason to put all your code in here is that it is good programming practice for code organization and more importantly, this is the closest you get to writing pure Ruby code inside of your application. Further, it makes it easy to read and understand as all that you see in these model files is mostly Ruby code.

Here are some things you can put in your model files:

  • Custom scopes - These scopes contain database queries that will get called from the controller. Instead of putting all your database queries inside your controller, you can put them inside scopes for better flow.

  • Add defaults - When a new database record is created, you can have default values for some records. Though you can do this using SQL queries, I personally like to do them through defaults because it is more connected to the code and less to the SQL database.

  • Integrate validations - You can put your form validations inside the model file for better control.

  • Integrate callbacks - You can create actions or flows that start when a record is created or deleted, and these are known as callbacks.

  • Integrating database relationships - Unlike other programming languages like PHP, Ruby allows you to establish all database relationships in your model file.
    We will go through each of these aspects in the upcoming lessons.