Skip to content

4.1 Projects Model

Nicolas Erlichman edited this page Aug 18, 2022 · 4 revisions

Having already created the Company model and CRUD controller, we will now focus on creating our last model which is Project, which belongs to a company.

Projects

Our new model Project will have the following attributes:

- id: integer
- name: string
- description: string
- start_date: date
- company_id: integer

We will again use the power of rails generators for this:

foo@bar:~$ rails generate model Project company:references name:string description:string start_date:date
      invoke  active_record
      create    db/migrate/20220818191042_create_projects.rb
      create    app/models/project.rb
      invoke    test_unit
      create      test/models/project_test.rb
      create      test/fixtures/projects.yml

Let's now execute the migration by running this:

foo@bar:~$ rails db:migrate

Model

As we just saw on 3.1. Companies Model our Project model is now created.

Relations

Our Project already belongs to a Company, but we need indicate that our company has many projects. To do that, we can use the keyword has_many on the Company side.

class Company < ApplicationRecord
  ...
  has_many :projects, dependent: :destroy
  ...
end

Validations

We add a validation to avoid Projects with empty names

class Project < ApplicationRecord
  ...
  validates :name, presence: true
  ...
end

Then we create a new migration to set our nullable condition to our projects names

foo@bar:~$ rails generate migration MakeProjectNamesNonNullable

We now have to edit the new migration to introduce the new nullable condition by replacing the contents with:

class MakeProjectNamesNonNullable < ActiveRecord::Migration[7.0]
  def change
    change_column :projects, :name, :string, null: false
  end
end

Run the migration and you are good to go.

foo@bar:~$ rails db:migrate

Next: 4.2 Projects Controller

Clone this wiki locally