Polymorphic associations in Ruby on Rails
Join the DZone community and get the full member experience.
Join For FreeWe 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.
Published at DZone with permission of Tim Millwood, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments