In this lesson, we will introduce the concept of models in our Ruby web application and then loading them with Zeitwerk.

Let's revisit the controller class we added in the previous article on controllers.

# controllers/articles_controller.rb

require_relative "application_controller"

class ArticlesController < ApplicationController
  def index
    @title = "Write Software, Well"
    @tagline = "Learn to program Ruby and build webapps with Rails"
  end
end

The @title instance variable is accessed in the ERB view as follows:

<%# views/articles/index.html.erb %>

<header>
  <h1>
    <%= @title %>
  </h1>
  <p>
    <%= @tagline %>
  </p>
</header>

This works fine, but as the data we want to display gets complicated in size and shape, it doesn't make sense to store it in separate variables. For example, suppose we want to display a post, with its title and body. With separate variables, you might write this:

# controllers/articles_controller.rb

require_relative 'application_controller'

class ArticlesController < ApplicationController
  def index
    @title = "Write Software, Well"
    @tagline = "Learn to program Ruby and build webapps with Rails"

    @post_title = "Rails Companion"
    @post_body  = "Let's build a web application in Ruby, without Rails!"
  end
end

A better way to organize this data is to group the related variables together and encapsulate them inside proper Ruby objects, also called models in the Rails. For example, the above properties could be moved to a Post class.

The benefit of models is that you can move the common operations on the data to the objects methods, and it keeps your controllers nice and clean. Models also provide a place to keep all your business logic together, separate from the view or controller's logic.