6. Create Models

September 2015 · 2 minute read

In this example I will be using rake and Active Record Migrations to create a new income model backed by a posgreSQL database.

-First I’ll need to ensure I have included postgreSQL

PostgreSQL is the default database on Mac OS X Server as of version 10.7. The standard version of Mac OS X includes only the PostgreSQL command line client utilities*

-Ensure the correct gem is included in the Gemfile

-Update the app/config/database.yml file. You will see that the default database used with Ruby on Rails is sqlite3. We are going to use posgreSQL

Having changed the development environment, I need to run a migration to ensure that rails knows I am now using posgreSQL. This can be done with the following terminal command.

$ bin/rake db:migrate RAILS_ENV=development

Now I can generate a new model for income

$ rails generate model income wages:int other_income:int income_total:int

This will create a new model under app/models/

This will also create a new file under app/db/migrate which shows a record of all migrations that have been created.

I get an error because I’ve given the wrong instructions to the migration

The update below specifies whether each field is allowed to be null or not, I also should have migrated “integers” not “ints” - I make these updates directly in the migration file with sublime

Next I will need to re-create and migrate the database to update the changes, this can be done in one simple command

$ rake db:drop && rake db:create && rake db:migrate

If you are watching your screen in sublime, you can see the migration quickly disappear and reappear indicating that the drop, create, migrate was successful. Your terminal will also confirm this

Now that I have successfully migrated an income model, it’s time to create a view and controller to be able to access that information visually.

Working Example Reference https://github.com/SelenaSmall/My_Budget

*Ref

*Resources