At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

Everything You Must Know About Associations In Rails

  • By Amit Kumar
  • December 26, 2018
  • 3274 Views

Association is an important term for the rails developer as it gives you the power to induce relationship between the active records models to make a better database structure. It provides you simpler query option compared to raw database queries.

Why We Need Association?

Association is the relationship between the active record models. In other words, Association will help us to perform queries and operations on the active record in an easy way.

Types of Associations:

  1. One-to-one
  2. One-to-many
  3. Many-to-many
  4. Polymorphic one-to-many

One-to-One Association:

One-to-One association indicates a record which holds only one instance from another model.
For example In an application one user can have only one address, in that case, you can say user model has “has_one” association with an address model.

Sample model code:

class User < ApplicationRecord
 has_one :address
end
 
class Address< ApplicationRecord
 belongs_to :user
end

 
In above example one model should contain has_one method invocation and other model should have belongs_to. Basically, it used to describe which model contains the foreign key reference for the other model. So, In above case Address model contains the reference.

One-to-many:

One-to-many Association is one of the most common association which is used to create relation between active record models, It indicates each instance of a model A can have one or more than one relation with another model B, and model B will belongs_to only one model A.
For example Suppose in an application, users are allowed to write multiple blogs and in the models you can see how it will look like,
Sample model code:
class User < ApplicationRecord
has_many :blogs
end
class Blog< ApplicationRecord
belongs_to :user
end
In the above example Blog model contains the foreign key reference. In this case, basically one user can have multiple records in blogs model but blog will belong to only one record of the User.

Related: Installation And Uses Of Active Admin In Rails Application

 

Many-to-many:

Many-to-many Association is bit complex, this can be handled in two ways “has and belongs to many” and “has many through” relation.
First, let’s understand “has and belongs to many”
A “has_and_belongs_to_many” association will create a direct many-to-many connection with other models. It is easier than the has_many through, as it only requires has_and_belongs_to_many from both models, and we just need to create an extra migration to connect two tables.
For example
Let’s assume the user who can have many roles and the same role may contain many users so in that case, the models would be like this:

Sample model code:

class User < ApplicationRecord
 has_and_belongs_to_many :roles
end
 
class Role < ApplicationRecord
 has_and_belongs_to_many :users
end

 
Now we need to create a migration for this association,

class CreateUserRoles < ActiveRecord::Migration
 def change
   create_table :user_roles, id: false do |t|
     t.references :user, index: true, foreign_key: true
     t.references :role, index: true, foreign_key: true
   end
 end
end

 
This is a very simplest approach, but you don’t have the direct access to related model objects, you can only get the references of two models. but you can achieve it through “Has Many Through”.
Now we will see the “Has Many Through”
Another way to define “many-to-many association” is to use the “has_many through” association type. Here we need to define a separate model or we can call as third model to create a relation between first two models.
For example,
let’s take the same above example but the only thing differs here is, Additionally, one extra model will be added.
Therefore all these three models will look like,

Sample model code:

class User < ApplicationRecord
 has_many :user_roles
 has_many :roles, through: :user_roles
end
 
class UserRoles < ApplicationRecord
 belongs_to :user
 belongs_to :role
end
 
class Role < ApplicationRecord
 has_many :user_roles
 has_many :users, through: :user_roles
end

 
Here we no need to create a separate migration like we did in the previous example. Also, it has some good advantages like – It allows you to do things like “user.role” to get a list of all connected models instance and also will allow you access the specific data to the related model.

Best To Read: How To Build Rock Solid Ruby On Rails App With BDD

 

Polymorphic one-to-many:

Polymorphic Association is one of the most advanced associations available in the rails, we can use this association when we have a model that belongs to many different models based on a single association.
For example – Assume we have users and story models in our application, and there is an option called comment for both users and the stories. So to make this scenario workable we need to use “Polymorphic Association” to make both models commentable.
Let’s see the model code:

Sample model code:

class Comment < ApplicationRecord
 belongs_to :commentable, polymorphic: true
end
 
class Employee < ApplicationRecord
 has_many :comment, as: :commentable
end
 
class Product < ApplicationRecord
 has_many :comment, as: :commentable
end

 
We can try something extra for allowing other model to access the data by creating an interface. And for declaring interface we just need to add two columns: foreign key and type. Once you’re done with these changes we just need to run the migration and the migration will look like below,

class CreateComments < ActiveRecord::Migration
 def change
   create_table :comments do |t|
     t.text :body
     t.integer :commentable_id
     t.string :commentable_type
     t.timestamps
   end
 
   add_index :comments, :commentable_id
 end
end

 
[contact-form-7 404 "Not Found"]
Okay guys, we’re almost done with all the associations in Rails, now you can start practicing association in rails to avoid or reduce the length of raw queries. We encourage your tips on Association to add more quality tactics on this blogs. Post us your thoughts in the comment section.
Building Rails application? Like to hear more from Ruby On Rails experts? Don’t miss out to read more from the great minds in the industry!

Contact us today to get free 20 hrs of consulting & proof of concept from experts”

 

Amit Kumar

Amit Kumar | Software Engineer | Blockchain Developer | Blogger | at Agira Technologies, With 2 years of experience in Web Development & strong expertise in Ruby On Rails, AngularJS, CMS he is working around diverse projects & a perfect wanderer perceiving peace in traveling.