Rails and Postgres

I’m slowly grasping the connection between Rails and Postgres. I’m starting to feel like this is the key to the Model-View-Controller system, but I’m still working on fully wrapping my head around this bad boy.

Luckily, I took copious notes during most Postgres/Rails lesson, and you can read them here.

Getting Started

You must first download PostgreSQL, and follow the prompts to learn its console line commands.

You must start by initializing a database and then creating a table.

When you create a table, you must include the fields and data types that all of your entries will have. Here’s an example from the exercise in the course, where we created a contact book:

CREATE TABLE contacts ( id SERIAL PRIMARY KEY, first_name TEXT, last_name TEXT, date_of_birth DATE, street_address_1 TEXT, street_address_2 TEXT, city TEXT, state TEXT, zip TEXT, phone TEXT, notes TEXT, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
Enter fullscreen mode
Exit fullscreen mode

The id field will always be a SERIAL PRIMARY KEY to indicate it should auto-increment and that this will be the primary key of your table.

After creating your table, you can launch it to prime it for editing/access with the psql command, or by using rails db.

To link your Rails project with your database, you have to edit your database.yaml file. Change rails_template_development on line 27 to your database’s name and it’ll find it on your computer.

Also, you can access Rails’ built-in database GUI by launching bin/server and navigating to rails/db in your project. From there, you can perform CRUD operations on data or observe.

Models

You must interface with your database via a Model, which Rails provides as an easy way to structure your database actions. Models are Ruby classes that “talk to the database, store and validate data, perform the business logic, and otherwise do the heavy lifting”.

These models inherit methods from Rails’s built-in ActiveRecord class, which lets them do many different moves. Each model represents a single row of data, so they’re named singularly after the name of the table (i.e. a model named Contact for a table named contacts). This naming convention helps Rails automatically locate the table that the model represents.

We can operate on the data several ways once we complete setup, but I’m calling it on Rails/Postgres until we do it next week as a class.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top