Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Polymorphic associations in Ruby on Rails

DZone's Guide to

Polymorphic associations in Ruby on Rails

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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
end

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
end

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

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
@post.save

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.



Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}