Skip to content

The problem with polymorphism

barunio edited this page Jan 10, 2012 · 1 revision

The problem with polymorphism

Polymorphism is an incredibly useful tool to build well structured applications. But the way it's implemented with Rails is reflects very poor database design.

Consider the example of polymorphism that's outline in the Rails Guides:

class Picture < ActiveRecord::Base
  belongs_to :imageable :polymorphic => true
end
class Employee < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end

As the image shows, imageable_id can reference either the employees table or the products table. This is a bad thing from the perspective of the database, because it violates the fundamental principle that one column in a table should refer to one thing. More practically, it means that it is impossible for us to create any sort of database constraint to make sure imageable_id makes sense.

Clone this wiki locally