Rails Coach

Polymorphic Associations


Listen Later

Rails has the concept of Polymorphic associations, which are associations that can be of different data types. For example, let’s say we have a Comment model. A comment in your app can be on a post or a page. Rather than creating a PostComment model and a PageComment model, you can set up your Comment model to have a polymorphic association to a Page or a Post.
Generally people call these associations “something-able”. In this case, it would be commentable.
Here’s a quick code sample:
class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true
end
class Page < ActiveRecord::Base has_many :comments, :as => :commentable
end
class Post < ActiveRecord::Base has_many :comments, :as => :commentable
end
The only other thing you need to know is the database structure. On the database, you need two columns. A [polymorphic-association-name]_type string column and [polymorphic-association-name]_id integer column. In this case, it would be “commentable_type” and “commentable_id”.
...more
View all episodesView all episodes
Download on the App Store

Rails CoachBy Charles Max Wood

  • 4.7
  • 4.7
  • 4.7
  • 4.7
  • 4.7

4.7

3 ratings


More shows like Rails Coach

View all
Teach Me To Code » Screencasts by Charles Max Wood

Teach Me To Code » Screencasts

11 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

234 Listeners

iPhreaks by Charles M Wood

iPhreaks

17 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

45 Listeners

The Freelancers' Show by Charles M Wood

The Freelancers' Show

23 Listeners

React Native Radio by Jamon Holmgren, Robin Heinze, Mazen Chami

React Native Radio

59 Listeners

My JavaScript Story by Charles M Wood

My JavaScript Story

4 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

62 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

21 Listeners

Adventures in Angular by Charles M Wood

Adventures in Angular

15 Listeners