-
Notifications
You must be signed in to change notification settings - Fork 0
4.1 Projects Model
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.
Our new model Project will have the following attributes:
- id: integer
- name: string
- description: string
- start_date: date
- company_id: integerWe 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.ymlLet's now execute the migration by running this:
foo@bar:~$ rails db:migrateAs we just saw on 3.1. Companies Model our Project model is now created.
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
...
endWe add a validation to avoid Projects with empty names
class Project < ApplicationRecord
...
validates :name, presence: true
...
endThen we create a new migration to set our nullable condition to our projects names
foo@bar:~$ rails generate migration MakeProjectNamesNonNullableWe 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
endRun the migration and you are good to go.
foo@bar:~$ rails db:migrate