Get Active!...Record
Tags: beginners, ruby, rails, activerecord
Published: 2021-08-18 05:04:16

![PLo Hyphy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p3v5clbvs91r0bo2on6x.gif)

Active Record is a Ruby gem that allows to you easily create, maintain, manipulate your database. It is an ORM (Object Relational Mapping), which means it lets you interact with data in your database as though it were a normal Ruby object. 

For example if we have a dogs database, we can use Active Record to grab all our dogs with a simple:
```ruby
Dog.all
```

<br>
#<center>. . .
<br>

#Active Record Basics

* **Naming Conventions**
 * Pluralize the database tables associated with your class. Class name would be singular with the first letter capitalized and written in CamelCase. Table name is plural, all lowercase, and written in snake_case.
```
Model Class - Dog
Database Table - dogs
```

* **Create Active Record Models**
 * Subclass the *ActiveRecord* class. This will allow your class to inherit all the methods within the subclass.
```ruby
class Dog < ActiveRecord::Base
end
```

* **CRUD** (Create)
 * Active Record creates an object and saves it to the database instead of only creating a new instance.
```ruby
roscoe = Dog.create(name: "Roscoe", breed: "Mix")
```

* **CRUD** (Read)
 * Accesses data within our database. There are other read methods available [here](https://guides.rubyonrails.org/active_record_querying.html).
```ruby
Dog.all
# Returns all our dogs

Dog.first
# Returns the first dog

Dog.find_by(name: "Roscoe")
# Returns the first dog named Roscoe

Dog.where(breed: "Mix")
# Returns all dogs with a breed of "Mix"
```

* **CRUD** (Update)
 * Modify an attribute then save it to the database.
```ruby
albert = Dog.find_by(name: "Albert")
albert.update(name: "Alby")

# Bulk update
Dog.update_all "adopted = True"
```

* **CRUD** (Delete)
 * Remove object from the database.
```ruby
alby = Dog.find_by(name: "Alby")
alby.destroy
```

* **Migrations**
 * A way to alter the structure of your database. This is stored in migration files and executed using [rake](https://www.rubyguides.com/2019/02/ruby-rake/).
```ruby
class CreateDogs < ActiveRecord::Migration[6.0]
  def change
    create_table :dogs do |t|
      t.string :name
      t.string :breed
      t.boolean :adopted
    end
  end
end
```

<br>
#<center>. . .
<br>

#Active Record Advanced

* **Associations**
 * Sets up a connection between two models. 
 * **Belongs_to** connects each instance of the declaring class (Dog) to one instance of the other class (Owner). 
 * **Has_many** is on the opposite of the belongs_to connection and means the the declaring class (Owner) has zero or more instances connections of the other class (Dog).
```ruby
class Dog < ActiveRecord::Base
  belongs_to :owner
end

class Owner < ActiveRecord::Base
  has_many :dogs
end
```

* **Pluck**
 * Returns an array of just the attribute you provide.
```ruby
Dog.pluck(:name)
# => ["Roscoe", "Alby", "Fido"]
```

* **Joins**
 * Query one model based on data from a related table. Referencing how our Associations is set up:
```ruby
Owner.joins(:dogs)
```

* **Scope**
 * Custom queries that return an [ActiveRecord::Relation](https://www.theodinproject.com/paths/full-stack-ruby-on-rails/courses/ruby-on-rails/lessons/active-record-queries). You use scopes when you have a custom query that you will use in other places so you don't have to duplicate code.
```ruby
class Dog < ActiveRecord::Base
  scope :mix_breed, -> { where("breed = Mix") }
end
```

<br>
#<center>. . .
<br>

#Conclusion
This was just a small sample of what Active Record can do. If you'd like to learn more I will provide some links below. Happy coding!

<br>
#<center>. . .
<br>

#Resources
[Active Record Basics](https://guides.rubyonrails.org/active_record_basics.html)
[Active Record Associations]
(https://guides.rubyonrails.org/association_basics.html)
[Active Record Query]
(https://guides.rubyonrails.org/active_record_querying.html)
[Active Record Migrations]
(https://guides.rubyonrails.org/active_record_migrations.html)
[Scopes](https://www.rubyguides.com/2019/10/scopes-in-ruby-on-rails/)