Skip to content

Instantly share code, notes, and snippets.

@overdrivemachines
Created November 17, 2021 06:48
Show Gist options
  • Save overdrivemachines/1384396d31b05d1bc4bb967a5a574037 to your computer and use it in GitHub Desktop.
Save overdrivemachines/1384396d31b05d1bc4bb967a5a574037 to your computer and use it in GitHub Desktop.
Active Record Basics & Migrations

Naming Conventions

Model Class - Singular: BookClub DB Table - Plural: book_clubs

Schema Conventions

  • Foreign keys - Singularized_table_name_id: item_id, order_id
  • Primary keys - id
  • created_at
  • updated_at
  • lock_version - Optimistic Locking
  • type - Single Table Inheritance
  • (association_name)_type - Polymorphic Associations
  • (table_name)_count - Cache number of objects: comments_count

CRUD

Create

user = User.create(name: "David", occupation: "Code Artist") user = User.new user.name = "David" user.save

Read

users = User.all user = User.first user = User.find_by(name: 'David') users = User.where(name: 'David', occupation: 'Code Artist').order(created_at: :desc)

Update

user = User.find_by(name: 'David')

Add Column(s)

rails g migration AddPartNumberToProducts part_number:string rails g migration AddPartNumberToProducts part_number:string:index rails g migration AddDetailsToProducts part_number:string price:decimal

Remove Column

rails g migration RemovePartNumberFromProducts part_number:string

Create Table

rails g migration CreateProducts name:string part_number:string

Join Table

rails g migration CreateJoinTableCustomerProduct customer product

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment