DEV Community

JckSmith
JckSmith

Posted on

So you Want to use Active Record?

So you are getting into ruby and you come across this "Active Record" you have no idea what it is or what it does. Luckily it's quite easy!

"What is Active Record?" Well, in it's simplest term, it is an ORM (Object Relational Mapping), It can make fetching and representing data easier, while not making us write our own custom ORMs.

"That's cool, but what is an ORM?" Object Relational Mapping, AKA ORM, is a technique that connects objects of an application to tables in a relational database management system, Using this, we can store and retrieve properties and relationships of the objects without writing SQL statements directly.

Active Record closely follows the standard ORM model, which is...

  • Tables map to classes
  • Rows map to objects
  • Columns map to object attributes

Lets see how we can make associations between models, Lets say you have two files, song.rb and genre.rb, they would look like so...

class Song < ActiveRecord::Base
end
Enter fullscreen mode Exit fullscreen mode

and

class Genre < ActiveRecord::Base
end
Enter fullscreen mode Exit fullscreen mode

We can connect these models through association, which of there are three.

  1. one-to-one- When one item has exactly one of another item
  2. one-to-many- When one item can be a member of many other items
  3. many-to-many- When multiple items are related to one or more other items

You can indicate these by adding the declarations to your models: has_one, has many, belongs_to, and has_and_belongs_to_many.

Now lets see what relationships we should establish in the data system, and change up the code to look like...

class Song < ActiveRecord::Base
   belongs_to :genre
end
Enter fullscreen mode Exit fullscreen mode

and

class Genre < ActiveRecord::Base
   has_many :Songs
end
Enter fullscreen mode Exit fullscreen mode

This now indicates the relationship between song and genre, we used belongs_to in song because one song can belong to a single genre, and then we used has_many in genre, because one genre can have multiple songs. Now these two models are connected by the relationship we provided them and we can then us them accordingly.

In conclusion, Active Record is an ORM, which is a way to retrieve and store data in the database without writing SQLs. Active Record supports three different associations, one-to-one, one-to-many, and many-to-many and we can use those to connect the models to be used together.

Top comments (0)