The Road Ahead – Making Active Record Your New Best Friend – What is Active Record?



The Road Ahead – Making Active Record Your New Best Friend – What is Active Record?

0 0


active-record

Active Record Presentation for Women Who Code DC

On Github kdmcclin / active-record

The Road Ahead

Making Active Record Your New Best Friend

What is Active Record?

Active Record is what's called an object-relational mapper (ORM). In essence it acts as a go between or bridge between your app's objects and the database.

Why is it useful?

As fun as writing SQL can be, ActiveRecord's special syntax enables you to avoid having to write complicated queries. Instead it translates this syntax into the SQL for you.*

**Your ActiveRecord command** ``` Person.last ``` **The resulting SQL command** ``` SELECT `people`.* FROM `people` ORDER BY `people`.`id` DESC LIMIT 1 ```
*You can still write SQL with ActiveRecord if you want or need to.

Two way street

ActiveRecord also connects data flowing from your app back to the database.

Do you have a form where users are signing up, creating a post, or adding a writing prompt?

**The ActiveRecord command** ``` Prompt.create(text: "This is a writing prompt example") ``` **The resulting SQL command** ``` INSERT INTO "prompts" ("created_at", "text", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", "2017-01-25 17:59:20.333595"], ["text", "This is a writing prompt example"], ["updated_at", "2017-01-25 17:59:20.333595"]] ```

How do I set it up for my Rails app?

  • ActiveRecord is a gem that is included by default when you create a new Rails project
  • In order to set up the connections between different tables in the app's database, you need to specify relationships
    • You do this in your model and migration files
  • These relationships enable you to use ActiveRecord to access say, the orders of a particular user, or even a more complex query like totalling up the profit made on orders where the product had the word "green" in its title somewhere

Basic Active Record Relationships

one-to-one, one-to-many, many-to-many

One to One

  • The table of the belongs_to model contains a column with the foreign key (often id) of the has_one model
  • Not always clear when to use one
  • Users and social media profiles
    • A user only has_one Facebook profile, and that profile only belongs_to that user
###Example Models ``` class User < ActiveRecord::Base has_one :profile validates :username, presence: true, uniqueness: true end ``` ``` class Profile < ActiveRecord::Base belongs_to :user #validations and other methods would go here end ```
###So When Do I Use It? One indicator: the potential for a lot of empty fields ``` class CreateProfiles < ActiveRecord::Migration def change create_table :profiles do |t| t.string :name, null: false t.string :picture_url t.string :current_city t.datetime :birthday t.string :hometown t.text :quotes t.belongs_to :user t.timestamps end add_index :profiles, :user_id end end ```

Think of it Like a Spreadsheet

Profiles Table

Id Name Picture Url Birthday User Id 1 Katherine http://placehold.it/350x150 "2016-05-06 07:16:22" 5812 2 Darrell http://placehold.it/350x150 "2016-05-06 07:16:22" 8032 3 Travis http://placehold.it/350x150 "2016-05-06 07:16:22" 45678

Think of it Like a Spreadsheet

Users Table

Id Username Password 5812 katherine1234 #awesomefakepassword# 8032 darrell1234 #awesomefakepassword# 45678 travis1234 #awesomefakepassword#

One to Many

  • Very common
  • Like one to one, the table of the belongs_to model contains a column with the foreign key (often id) of the has_many model
  • Users and orders
    • A user has_many orders, and each order only belongs_to that user
###Example Models ``` class User < ActiveRecord::Base has_many :orders has_many :comments validates :username, presence: true, uniqueness: true validates :email, presence: true, uniqueness: true end ``` ``` class Order < ActiveRecord::Base belongs_to :user validates :confirmation_number, presence: true end ```
###Example Migration ``` class CreateOrders < ActiveRecord::Migration def change create_table :orders do |t| t.string :confirmation_number t.string :shipping_method t.datetime :date_placed t.belongs_to :user t.timestamps end add_index :orders, :user_id end end ```

Think of it Like a Spreadsheet

Users Table

Id Username Email Password 4923 katherine1234 katherine@example.com #awesomefakepassword# 6538 darrell1234 darrell@example.com #awesomefakepassword# 92304 travis1234 travis@example.com #awesomefakepassword#

Think of it Like a Spreadsheet

Orders Table

Id Confirmation Number Shipping Method User Id 1 CA11TKA201 1 Day 4923 2 KF22BNA571 Ground 92304

Many to Many

  • Also very common
  • Movies and genres
    • Genres can contain many movies, and those movies can belong to many genres
  • Join table contains the foreign keys (ids) of what's connected to it
  • Two ways of describing the relationship
    • has_many JOINTABLE & has_many OTHERTABLE through JOINTABLE
    • has_and_belongs_to_many (Rails/ActiveRecord magic creates the join table)
###Example Models ``` class Genre < ActiveRecord::Base has_many :movie_genres has_many :movies, through: :movie_genres end ``` ``` class Movie < ActiveRecord::Base has_many :movie_genres has_many :genres, through: :movie_genres end ``` ``` class MovieGenre < ActiveRecord::Base belongs_to :genre belongs_to :movie end ```
###When to Use has_and_belongs_to_many ``` class CreateMovieGenres < ActiveRecord::Migration def change create_table :movie_genres do |t| t.belongs_to :movie t.belongs_to :category t.timestamps end end end ``` When your join table only contains the foreign keys(ids) and no other useful information.

Think of it Like a Spreadsheet

Genres Table

Id Name 1 Animation 2 Kids 3 Documentary

Think of it Like a Spreadsheet

Movies Table

Id Title 1 Zootopia 2 13th 3 How to Train Your Dragon

Think of it Like a Spreadsheet

Movie Genres Table

Id Movie Id Genre Id 1 2 3 2 1 1 3 1 2

t.what_now?

  • t.belongs_to, t.references, and t.integer
    • Everyone has their own preference, but any of these will work
    • t.belongs_to :user
    • t.references :user
    • t.integer :user_id
      • Note: when you use t.integer you need to specify the id because integer just means a number
      • With t.belongs_to or t.references the Rails/ActiveRecord magic can safely assume what you mean

More resources