Active Record has_many Association

Abel Gechure
2 min readJan 29, 2021

For my Sinatra project I decided to build a simple book tracker applications that performs all the CRUD actions. I used Active Record as my ORM and my application took advantage of the has_many and belongs_to association macros available from Active Record.

ERD diagram showing has_many association

I worked with two models in my application. The user and book models. I created a has_many relationship between the models and it simply reads a user has many books and a book belongs to a user.

In database terms, this association means that my book class will have a foreign key from the users table hence associating a user instance to a book instance.

When you declare a has_many association, the declaring class which in this case is the User class will automatically gain 17 methods related to the association.

Each instance of the User model will have these methods:

books
books<<(object, …)
books.delete(object, …)
books.destroy(object, …)
books=(objects)
book_ids
book_ids=(ids)
books.clear
books.empty?
books.size
books.find(…)
books.where(…)
books.exists?(…)
books.build(attributes = {}, …)
books.create(attributes = {})
books.create!(attributes = {})
books.reload

here is a brief example of how you can use the methods. If you are on Sinatra open up tux on the terminal and play around with these methods and get to learn what they do, likewise if you are running rails just type rails console or rails c and in your console do the same.

books

Returns a relation of all of the associated objects and if there is no association, it returns an empty relation. @books = @user.books

books<<(object, …)

Adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model. @user.books << @book_one

books.delete(object, …)

Removes one or more objects from the collection by setting their foreign keys to NULL . @user.books.delete(@book_one).

For the rest of these examples I urge you to visit https://guides.rubyonrails.org/kindle/association_basics.html

--

--