Rails Active Record(Model) revierse polimorphic


It’s easy to do polymorphic associations in Ruby on Rails(Acitve Record):

  • A Picture, a Video can belong to an Article
  • A Picture can belong to either an Article

This example shows how to create an ArticleElement join model that handles the polymorphic relationship.


🐞 Model

class Article < ActiveRecord::Base
has_many :article_elements
has_many :pictures, through: :article_elements, source: :element, source_type: 'Picture', class_name: 'Picture'
has_many :videos, through: :article_elements, source: :element, source_type: 'Video', class_name: 'Video'
end

class Picture < ActiveRecord::Base
has_one :article_element, as: :element
has_one :article, through: :article_elements
end

class Video < ActiveRecord::Base
has_one :article_element, as: :element
has_one :article, through: :article_elements
end

class ArticleElement < ActiveRecord::Base
belongs_to :article
belongs_to :element, polymorphic: true
end

🏀 Migration

class CreateArticles < ActiveRecord::Migration[5.0]
def change
create_table :articles do |t|
...

t.timestamps
end
end
end

class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
...

t.timestamps
end
end
end

class CreateVideos < ActiveRecord::Migration[5.0]
def change
create_table :videos do |t|
...

t.timestamps
end
end
end

class CreateArticleElements < ActiveRecord::Migration[5.0]
def change
create_table :article_elements do |t|
t.references :article, index: true
t.references :element, polymorphic: true, index: true

t.timestamps
end
end
end

🐝 Special Thanks

Reverse polymorphic associations in Rails

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!