Of Rails and Databases

Creating a Rails app without a Database is like building a beautiful library without putting any books on the shelves!

The main purpose of the internet is to share information. As such, a website isn’t very useful without the ability to store and retrieve information. Since Rails is simply a collection of Ruby code, it doesn’t have the ability to store long-term information by itself.

In order to store information, Rails needs to link to a database. A database is any software that can store information. There are several database softwares around such as MySQL, PostgreSQL, and others. Rails can be set up to store information to the database and retrieve it at a later time.

Being able to store data increases the functionality of any web application tremendously. This is the foundation of the internet as we know it, and the possibilities are endless in terms of what you can do with it!


Installation & Set Up

We’re using PostgreSQL in my coding bootcamp, but there are others as well. The same gorails.com page that describes how to install Rails also has instructions for installing databases. However, for this blog, I’ll be referring to PostgreSQL as my database (at least while I’m in bootcamp!)

The basic steps I followed for class are simply:

brew install postgresql
# To have launchd start postgresql at login:
ln -sfv /usr/local/opt/postgresql/*plist ~/Library/LaunchAgents

# Then to load postgresql now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
Take time to make your database set-up fairly solid from the beginning so that you can bask in your own awesomeness later!

Set Up

A Model is any code that saves data to a database.

In the workflow
Routes -> Controller -> View 
the Model will interact with the Controller.

To set up an app that uses a Model to interact with a Postgres database, use the following commands in your terminal:

  • Step 1: Create a new app that uses Postgres as a database
    rails new app_name --database=postgresql
  • Step 2: Change directories to the new app folder. 
    cd app_name
  • Step 3: Generate a new database. This is analogous to opening a new blank file in Excel.
    rails db:create
  • Step 4: Create a new controller. Note that the controller name should be plural. 
    rails generate controller Controller_names
  • Step 5: Create a new model. Note that the model name should be the same as the controller name, but singular. For the attributes, if you don’t specify a type, it will default as a string. Attribute types are the same as in Ruby (string, int, float, etc)
    rails generate model Controller_name attribute1:attribute1_type attribute2:attribute2_type ...etc
  • Step 6: Migrate the Model into the Database. This is analogous to adding headings to each column in Excel. 
    rails db:migrate

At this point, you will have a brand new Rails app that is linked to a database with a defined Controller and Model. To see your app in action, run the following commands:

  • To open your Rails Console (basically irb with your Rails app installed): rails console
  • To start your server, open a new terminal tab (Command-T) and run: rails server
  • To open your Rails app in a browser, visit localhost:3000.

Model Methods: CRUD

Rails Models have 4 main functions that go by the acronym CRUD: Create, Read, Update, and Destroy. These are the only 4 things that Rails Models are able to do. In order to populate our database, we can use these four functions in our terminal after we’ve called the command rails console.

CRUD: Create, Read, Update, Destroy

Create

Use the follow code to assign a new instance of your module into a variable.

item = ModelName.new({attribute1:"value1", attribute2:"value2", attribute3:"value3" etc})
item.save

In this example, we are assigning a new instance for the model “ModelName” to the variable “item”. The first command only saves the new instance into a variable, but this information will be lost if you overwrite the variable or exit out of your terminal! We must use the .save method in order to save the instance into the database!! Otherwise, all the work you did to create a new instance will be lost.

Some tips when creating new instances:

  • All the attributes of the new instance are stored in a hash, so it doesn’t matter what order you enter the data.
  • You don’t even have to fill in all the attributes, but it’ll assign a nil value to anything that hasn’t been assigned.
  • Be very careful about making sure your quotes are closed properly.
  • Remember that model names are the same as controller names, but singular. Make sure to the singular to create your model instances.
  • Don’t forget to save your instance! I know I’ve mentioned it previously, but it’s worth repeating!

Another important thing to note is that Rails will automatically create an ID number for each instance in the database. This is important because this means each enter will have at least one unique identifier. This makes it easier to differentiate multiple similar entries; for example, if you had two users named John Doe.

Read

There are several ways to read data in the database. Here are a few of them:

items = ModelName.all
first_item = ModelName.first
last_item = ModelName.last
pink_item = ModelName.find_by(pink_attribute:"pink_value")
item.attribute_name
  • The .all method will store an array of instances into the specified variable.
  • The .first method will find the instance in the database with ID = 1.
  • The .last method will find the instance in the database with the highest ID number.
  • The .find_by method will allow you to search the database using a specific attribute.

To find a specific attribute of a specific model object, use the following code:

item = ModelName.find_by(known_attribute:"known_value")
item.unknown_attribute

For example, if you knew John’s Smith’s email address but wanted to look up his phone number, the code might look something like:

jsmith = Contacts.find_by(email:"jsmith@email.com")
jsmith.address

Update

In order to update an existing item in the database, first you must find it and assign it to a variable before updating it.

To do this, use the following code:

item = ModelName.find_by(attribute1:"value")
item.attribute2 = "updated value"
--OR--
item.assign_attributes({attribute2 = "updated value"})
item.save

Destroy

Just like Update, in order to delete an existing item from the database, you must first find it and assign it to a variable.

The code to do this is as follows:

item = ModelName.find_by(attribute1:"value")
item.destroy

While using Rails with databases seems simple enough, this fairly straightforward relationship can be used to build quite powerful applications.

In class, we’ve already been able to build some working small-scale working apps such as a contact list app and an app with several simple games. We’ve recently began working on a mini-capstone project in which we build functionality as we learn new concepts. It’s amazing how much you can build with a small amount of knowledge!