Over a million developers have joined DZone.

Polymorphic associations in Ruby on Rails

DZone's Guide to

Polymorphic associations in Ruby on Rails

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

We have recently been working with a project where Polymorphic Associations have been used extensively. Here we'll give an example of how they can be used.

Imagine a school or college system where both students and teachers can add posts. The post has an author but this author could be a student or a teacher. The students and teachers can also add many posts. Therefore we need an association between the Student, Teacher and Post models.

$ rails generate model post author:references{polymorphic}:index title:string body:text
$ rails generate model student name:string email:string
$ rails generate model teacher name:string email:string office:integer

Here we've created the post model with the author reference set as polymorphic and an index, along with a title string and body text. The student and teacher models both features a name and email, but with the office number added for a teacher.

class Post < ActiveRecord::Base
  belongs_to :author, polymorphic: true

The Post model will already be setup correctly, but we need to add has_many to the Student and Teacher models.

class Student < ActiveRecord::Base
  has_many :posts, as: :author

class Teacher < ActiveRecord::Base
  has_many :posts, as: :author

Now when creating a post we can just pass in a Student or Teacher object to add the author association. For example if the logged in Student or Teacher is fetched as a current_user helper method we can do the following:

@post = Post.new(post_params)
@post.author = current_user

or even using the posts association from the current_user.

@post = current_user.posts(post_params)

Either of these will set the current_user (whether that's a Student or Teacher) as the author of a post. When displaying posts we can return the Student or Teacher name with an erb element such as:

<%= @post.author.name %>

This only scratches the surface of polymorphic associations but gives an idea of how it works. You will find that once you start using them then they'll be common throughout the application.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.


Published at DZone with permission of Tim Millwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}