Skip to content

Instantly share code, notes, and snippets.

@patwey
Created October 28, 2015 00:11
Show Gist options
  • Save patwey/b43793dcb415e2a6b054 to your computer and use it in GitHub Desktop.
Save patwey/b43793dcb415e2a6b054 to your computer and use it in GitHub Desktop.
Migrations, Databases, Models, and Relationships in Rails

Migrations, Databases, Models, and Relationships in Rails

Types of Relationships

  • One-to-One: One brain belongs to one person
  • One-to-Many: One cow has many stomachs
  • Many-to-Many: Many ideas belong to many people

Databases in Rails Apps

What's the difference between test, development and production databases?

  • Test dbs are wiped clean after each test and after all tests are run.
  • Development dbs store whatever you want, to help with development of the app.
  • Production dbs are the ones that are actually deployed. They store real data.

How do you create a Rails app from the command line with a postgres database?

  • rails new app_name --database=postgresql

Migrations

What files are created by typing rails g model ...?

  • a migration file including any fields specified in the command
  • a model inheriting from the ActiveRecord::Base
  • a model test file
  • a fixtures file

What's the difference between typing rails g model... and rails g migration?

  • rails g model creates a model, migration, model test file, and a fixtures file
  • rails g migration just creates a migration - useful for things that don't create a new model

Imagine that the items table has a category called quantity. What command would you type if you wanted to get rid of the quantity attribute?

  • rails g migration RemoveQuantityFromItems quantity:integer
  • Adding quantity:integer allows this migration to be reversable

Imagine that you have a table students. What is the ActiveRecord query that would return all students with the first name of Richard?

  • Student.where(name: 'Richard')

How would you update the student record with ID 4 to have a new phone number of "101-222-3333"?

  • Student.find(4).update(phone_number: '101-222-3333')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment