Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby on rails

What are ActiveRecord associations?

Zarish Nadeem

What is ActiveRecord?

ActiveRecord is the model in MVC architecture. It simplifies the details of SQL by treating items within the database as objects. ActiveRecord provides the following correspondence:

You can use simple Ruby syntax to work with data.

#This code will simply creates an object of person
#it will get all the atributes realted to it where 
#name matches Elif

person = Person.where(name:"Elif").first
person.age = 40

# The above code could replace SQL such that
# Select * From persons Where name = "Elif"
# Update persons SET age = 50 Where name = "Elif"

ActiveRecord follows naming conventions to map models and database schema.

Model / Class

Table / Schema





ActiveRecord associations

There are very few (or no) applications that have just one model. So, an application plausibly has a lot of models interacting with each other. A significant benefit of the ActiveRecord library is the ability to easily relate models to each other through relationships known as associations.


Consider a project xyz that has many bugs, and each of these bugs belongs to this specific project.


class Project < ApplicationRecord
  has_many :bugs, dependent: :destroy

class Bug < ApplicationRecord
  belongs_to :Project

With the association above, creating a bug is easy.

@bug = @project.bugs.create(published_at:

However, without associations, the code would appear as shown below.

@bug = Bug.create(published_at:, project_id:

Similarly, deletion is also easy with associations.


This will delete the project as well as all of its bugs. Without associations, the deletion of the project as well as all of its bugs will require more lines of code.

@bugs = Bug.where(project_id:
@bugs.each do |bug|

ActiveRecord allows an almost natural language mechanism of defining model relationships. In our Bug model, we say that Bug objects “belong_to” Project objects. In the Project model, we say that a Project object “has_many” associated Bug objects. The only thing you need to set up, other than the relationship itself, is a column in the Bugs table that enables the relationship to work. You need to store the ID of the associated project with each Bug object, so you need to add an integer column to Bugs called “project_id.” You can do this by creating a new migration and using a directive such as add_column :bugs, :project_id, or :integer, or by manually adding the column through another client with SQL.

Types of associations

  • belongs_to
  • has_many
  • has_one
  • has_many :through
  • has_one :through
  • has_and_belongs_to_many


ruby on rails

View all Courses

Keep Exploring