Polymorphic Association in Ruby on Rails

This article will discuss Polymorphic Association, an important concept in Ruby on Rails.

Consider the concept of building an application for which users and companies will register. Both models will have attributes that can be easily separated out as a model, such as a bio, profile_picture, etc. So, rather than including these attributes in User and Company models, they can be included in another model called Profile. In this scenario, the Polymorphic Association is used.

Here is how to start. First, create the models.

1
2
3
4
5
6
rails generate model User name
rails generate model Company name

rails generate model Profile bio profileable_id:integer profileable_type:string

rails db:create db:migrate

Make sure the models look like this:

1
2
3
4
# app/models/company.rb
class Company < ApplicationRecord
  has_one :profile, as: :profileable
end
1
2
3
4
# app/models/user.rb
class User < ApplicationRecord
  has_one :profile, as: :profileable
end
1
2
3
4
# app/models/profile.rb
class Profile < ApplicationRecord
  belongs_to :profileable, polymorphic: true
end

Now go ahead and test the implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
User.create(name: "John")
user = User.first
user.create_profile(bio: "I love reading books.")
user.profile
=> #<Profile id: 1, bio: "I love reading books.", profileable_id: 1, profileable_type: "User", created_at: "2020-05-08 09:38:24", updated_at: "2020-05-08 09:38:24">

Company.create(name: "Mintbit")
company = Company.first
company.create_profile(bio: "We are exporters of food stuff.")
company.profile
=> #<Profile id: 2, bio: "We are exporters of food stuff.", profileable_id: 1, profileable_type: "Company", created_at: "2020-05-08 09:56:07", updated_at: "2020-05-08 09:56:07">

profile = Profile.first
profile.profileable
=> #<User id: 1, name: "John", created_at: "2020-05-08 09:26:28", updated_at: "2020-05-08 09:26:28">

profile = Profile.second
profile.profileable
=> #<Company id: 1, name: "Mintbit", created_at: "2020-05-08 09:26:53", updated_at: "2020-05-08 09:26:53">

There you have it. Polymorphic Association has been successfully implemented in Ruby on Rails.