I recently had a conversation with an old friend who is in the process of learning Ruby on Rails. He had run into a problem with polymorphic associations and I recommended he try something I had done for another project using polymorphic associations. It turns out that it was a good solution to the problem, and since I haven't seen the pattern talked about elsewhere, I thought I should get it down on paper.

For the sake of example, let's say we're building a Tumblr clone, where the polymorphic association lives inside of a Post model, and the different kinds of posts are all models unto themselves. We could use single table inheritance, but maybe the models vary enough or the storage method differs enough that that's a bad idea. For that matter, Single Table Inheritance often just feels wrong.

Simplicity will work best in this case, so let's say that every post has a title, timestamps, and belongs to a user.

[ruby]
# db/migrate/001_create_posts.rb
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.string :title
t.references :user
t.integer :postable_id
t.string   :postable_type
t.timestamps
end
end

def self.down
drop_table :posts
end
end
# app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :postable, :polymorphic => true
end
[/ruby]

Before we even get into the different kinds of posts we might want to make, let's abstract this model so that we can tack it onto nearly any model in our application. How? A little bit of metaprogramming.

[ruby]
# lib/postable.rb
module Postable
def self.included(klass)
klass.instance_eval do
has_one :post, :as => :postable
alias_method_chain :post, :autocreate

[:title, :user, :created_at, :updated_at].each do |method|
delegate method, "#{method}=", :to => :post
end
end
end

def post_with_autocreate
post_without_autocreate || build_post
end
end
[/ruby]

What does this get us? Well, in just a few lines of code, we have saved ourselves from really having to think about this problem very hard again. Consider creating two kinds of posts, something like a quote post and a freeform text post (called a blob, in this example):

[ruby]
# db/migrate/002_create_quotes_and_blobs.rb
class CreateQuotesAndBlobs < ActiveRecord::Migration
def self.up
create_table :quotes do |t|
t.string :quotee
t.text :quote
end
create_table :blobs do |t|
t.text :content
end
end

def self.down
drop_table :quotes
drop_table :blobs
end
end
[/ruby]

I have deliberately chosen separate interfaces for these two kinds of model so I can show off some other stuff later. But to get them posting, all we need to do is include our "Postable" module and we are up and running:

[ruby]
# app/models/quote.rb
class Quote < ActiveRecord::Base
include Postable
end

# app/models/blob.rb
class Blob < ActiveRecord::Base
include Postable
end
[/ruby]

That's it. We can get started immediately by creating our forms. Because of the Postable interface we have created, both models will automatically have the fields on Post (and, in fact, will work transparently thanks to delegation). The only other thing we need to think about is creating a common interface back to the individual post types from the Post model. We can do this with a helper, the model, or we can take advantage of Rails' partial rendering and just create a views/quote/_quote.html.erb and views/blob/_blob.html.erb. Those views might look something like:

[ruby]
# app/views/blob/_blob.html.erb
<h2>
<%= blob.title %>
</h2>
<div class='byline'>
by <%= link_to blob.user.name, blob.user %> on <%= blob.created_at %>
</div>
<div class='blob-content'>
<%= blob.content %>
</div>
[/ruby]

I'll leave the quote partial as an exercise for the reader.

At this point, we can put all of our posts on a single page like this:

[ruby]
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.order_by('created_at DESC')
end
end

# app/views/posts/index.html.erb
<h1>All Posts</h1>
<%- @posts.each do |post| %>
<%= render post %>
<% end -%>
[/ruby]

The same technique can be used in a number of situations, such as many kinds of authenticable users with one login screen or some other sort of shared attributes. What's nice is that it is trivially extensible. You create a model with any extra fields that you need, include your module, and you're up and running.