Update 02/02/10: There are two new sections: Fixing method_missing and Handling attributes hash, which fix a few issues that popped up since first post.
If you aren’t interested in reading all the details you may want to make the long story short.
Imagine writing an online shop with different types of products. Normally all products would have common attributes such as title and price. Some attributes will likely differ. Tee may have size such as S, M, or L, while a Pen could have an ink_color. It’s easy to see that Tee is a Product, and so is Pen. We are looking at an is_a relationship. When I program this type of relationship I usually use inheritance.
end
class Tee < Product
end
class Pen < Product
end
This inheritance looks reasonable, but now we have to come up with relational database structure. We need to find a way to store tee’s own attributes, pen’s own attributes, as well as their common (product’s) attributes without duplication. Some databases (PostgreSQL) provide support for table inheritance, but it’s a specialized feature which ties you down to the given db.
Single Table Inheritance
ActiveRecord provides only one way to handle a is_a relationship which is Single Table Inheritance. You’d have to create a table looking somewhat like the following.
| id | type | price | title | size | ink_color |
+----+------+-------+-----------------+------+-----------+
| 1 | Tee | 1000 | tie-dye t-shirt | M | |
| 2 | Pen | 500 | ball pen | | blue |
+----+------+-------+-----------------+------+-----------+
The problem here is that all attributes are stored in the same table. It’s likely that soon the number of attributes will grow unmanageable, and most of them will always stay NULL since they’ll be specific to only one type.
Polymorphic has_one Association
A has_one association allows us to split out tees, pens, and products into three different tables. In fact — as you’re about to see — this is the only way to get what we want. The problem is that it creates a has_a relationship, and we want is_a. Since there isn’t much choice, we can make it look like we have an is_a relationship, which I’m about to show.
Multiple Table Inheritance (Simulated)
I was speaking with the awesome @fowlduck over at #railsbridge IRC channel about ways to achieve something like MTI with Active Record. He pointed me to a pastie where he implemented an MTI-like behavior and called it a “hydra” pattern, which I subsequently cleaned up a bit.
So we want to have 3 tables in the database.
- product_properties
- tees
- pens
belongs_to :sellable, :polymorphic => true, :dependent => :destroy
end
class Tee < ActiveRecord::Base
has_one :product_properties, :as => :sellable, :autosave => true
end
class Pen < ActiveRecord::Base
has_one :product_properties, :as => :sellable, :autosave => true
end
Immediately we can see duplicated code between Tee and Pen. This can be easily solved with a mixin.
def self.included(base)
base.has_one :product_properties, :as => :sellable, :autosave => true
end
end
class Tee < ActiveRecord::Base
include Sellable
end
class Pen < ActiveRecord::Base
include Sellable
end
Now comes another issue. Every time we want to access price or title attributes (stored in product_properties) we have to call @tee.product_properties.price. This isn’t very convenient, especially considering that product_properties has to be built first in case it doesn’t exist. So let’s ensure it’s always built by updating the module.
def self.included(base)
base.has_one :product_properties, :as => :sellable, :autosave => true
base.alias_method_chain :product_properties, :autobuild
end
def product_properties_with_autobuild
product_properties_without_autobuild || build_product_properties
end
end
Awesome, now product_properties is built automatically in case it doesn’t exist. We still have the method accessing issue though. For that I used method_missing.
def self.included(base)
base.has_one :product_properties, :as => :sellable, :autosave => true
base.alias_method_chain :product_properties, :autobuild
end
def product_properties_with_autobuild
product_properties_without_autobuild || build_product_properties
end
def method_missing(meth, *args, &blk)
if product_properties.public_methods.include?(meth.to_s)
product_properties.send(meth, *args, &blk)
else
super
end
end
end
Now if a method is missing from Tee or Pen instance it will be delegated to product_properties, which enables us to use @tee.price and @tee.title.
However, what about validations? Let’s say we want all products to always have a title, and we want to see an error appear on a Tee instance when ProductProperties#title is missing. Basically I want to completely remove product_properties from my sight as if it doesn’t exist, make it absolutely transparent. Let’s add the necessary validation in ProductProperties.
belongs_to :sellable, :polymorphic => true, :dependent => :destroy
validates_presence_of :title
end
And now let’s make all Sellable models respect the validation as if it’s their own.
def self.included(base)
base.has_one :product_properties, :as => :sellable, :autosave => true
base.validate :product_properties_must_be_valid
base.alias_method_chain :product_properties, :autobuild
end
def product_properties_with_autobuild
product_properties_without_autobuild || build_product_properties
end
def method_missing(meth, *args, &blk)
if product_properties.public_methods.include?(meth.to_s)
product_properties.send(meth, *args, &blk)
else
super
end
end
protected
def product_properties_must_be_valid
unless product_properties.valid?
product_properties.errors.each do |attr, message|
errors.add(attr, message)
end
end
end
end
Notice that I’m including an additional validator with the Sellable module. The validator collects all the errors on ProductProperties and adds them to parent class as if the errors are on a Tee or Pen itself.
As a nice finishing touch we can put this snippet into a Rails initializer.
def self.acts_as_product
include Sellable
end
end
# now we can say
class Tee < ActiveRecord::Base
acts_as_product
end
Although that’s a matter of taste.
Fixing method_missing
There is a problem with method_missing. It checks the array of public_methods on product_properties to find out if delegation should occur. This check will fail in cases like @tee.title_changed?. That’s a magic method and therefore will not be part of static method array. Well, this is an easy fix.
def method_missing(meth, *args, &blk)
product_properties.send(meth, *args, &blk)
rescue NoMethodError
super
end
As you can see, even magic methods will work this way. Only if a NoMethodError is thrown we withdraw back into super.
Handling attributes hash
In the comments Austin brought up a case where initializing new models like Tee.new(:title => "foo") will throw an unknown attribute error. That’s expected since we rely on method_missing for accessing ProductProperties attributes. Instead we should define accessor methods explicitly in our individual products. Thankfully, it’s not too hard to accomplish with our Sellable mixin. First we need to add a submodule ClassMethods with a class method that uses class_eval to magically generate missing attributes.
def define_product_properties_accessors
all_attributes = ProductProperties.content_columns.map(&:name)
ignored_attributes = ["created_at", "updated_at", "sellable_type"]
attributes_to_delegate = all_attributes - ignored_attributes
attributes_to_delegate.each do |attrib|
class_eval <<-RUBY
def #{attrib}
product_properties.#{attrib}
end
def #{attrib}=(value)
self.product_properties.#{attrib} = value
end
def #{attrib}?
self.product_properties.#{attrib}?
end
RUBY
end
end
end
I’ll walk through this code quickly. First we’re extracting only the columns that we want to access. When we call content_columns in the first line of the method, it already excludes a bunch of special columns such as id and type. We then manually subtract more columns we’d like to ignore, such as timestamps, and polymorphic type.
Next we iterate over each remaining attribute and creating instance methods for it, such as title, title= and (for completeness) title?. Having these accessors defined explicitly is enough for ActiveRecord to see them when performing mass assignment, etc. We can now do something like Tee.new(:title => "foo") without any problems. The extra cases such as @tee.title_changed? are still handled by method_missing so we’re good.
One more thing left. We need to run this method on the base class into which we include Sellable. Just need to add a couple of lines to the self.included hook.
base.has_one :product_properties, :as => :sellable, :autosave => true
base.validate :product_properties_must_be_valid
base.alias_method_chain :product_properties, :autobuild
# Add these two lines:
base.extend ClassMethods
base.define_product_properties_accessors
end
And we’re all set.
All together now
Here’s the full picture of everything we just did.
def self.acts_as_product
include Sellable
end
end
class ProductProperties < ActiveRecord::Base
belongs_to :sellable, :polymorphic => true, :dependent => :destroy
validates_presence_of :title # for example
end
module Sellable
def self.included(base)
base.has_one :product_properties, :as => :sellable, :autosave => true
base.validate :product_properties_must_be_valid
base.alias_method_chain :product_properties, :autobuild
base.extend ClassMethods
base.define_product_properties_accessors
end
def product_properties_with_autobuild
product_properties_without_autobuild || build_product_properties
end
def method_missing(meth, *args, &blk)
product_properties.send(meth, *args, &blk)
rescue NoMethodError
super
end
module ClassMethods
def define_product_properties_accessors
all_attributes = ProductProperties.content_columns.map(&:name)
ignored_attributes = ["created_at", "updated_at", "sellable_type"]
attributes_to_delegate = all_attributes - ignored_attributes
attributes_to_delegate.each do |attrib|
class_eval <<-RUBY
def #{attrib}
product_properties.#{attrib}
end
def #{attrib}=(value)
self.product_properties.#{attrib} = value
end
def #{attrib}?
self.product_properties.#{attrib}?
end
RUBY
end
end
end
protected
def product_properties_must_be_valid
unless product_properties.valid?
product_properties.errors.each do |attr, message|
errors.add(attr, message)
end
end
end
end
class Tee < ActiveRecord::Base
acts_as_product
end
class Pen < ActiveRecord::Base
acts_as_product
end
This can be easily adapted for any other use case besides products in a store. In fact, with some meta magic or code generation this can easily be made into a plugin which I encourage you to try and send me the link when you’re done. :)
[...] This post was mentioned on Twitter by RailsIndia, Maxim. Maxim said: So I finally posted that article on Multiple Table Inheritance with ActiveRecord. http://bit.ly/mti-ar (cc @fowlduck) [...]
Nice solution – nice and clear code!
This helped me improve my plugin a lot. Thanks! Great stuff.
I noticed you can’t do this:
Tee.new :title => ‘Foo’
You’ll get:
ActiveRecord::UnknownAttributeError: unknown attribute: title
Anyway around this?
Good point. Constructor remains oblivious to shared attributes. Off the top of my head I’m thinking about using a custom initializer in Sellable module, which would call super, but a gut feeling says there may be problems with that. Have to look more into how AR uses its initializers.
Check the article updates, I found a way to fix this issue.
Awesome Post! One question do you think this approach could be made generic? One piece of includable code that could be use to do the same thing for something like Animal -> Mammal/Fish and Vehical -> Car/Boat…etc
Ruby can eval itself, thus I don’t see why not. Then all you’ll need are the migrations for common-attribute table. Then again, you could write a rails generator for that. In fact, instead of eval’ing code – the whole thing could be implemented as rails generator. Let me know if you come up with something.
Thats pretty neat! Just something I was looking for I guess. I have the following problem to solve. I have a Playlist that has_many PlaylistItems. Each PlaylistItem can be either a Track, Album or Video. Track, Album and Video all have different attribs and only share maybe title and length as common attribs. I wonder if that could be designed using the solution you proposed here?
Sure, you can have these attributes separated into common table, but think twice before you do that. I probably should’ve explained this in the article, but I have only recently come to realize it better. In the article product attributes are not native properties to any particular items sold. For example, a t-shirt may differ in color, size, and material – but things like price, or flags – published, featured, do not constitute a t-shirt. They are not natural properties of a real t-shirt, they have nothing to do with one. It’s our given context (we are selling t-shirts in a store, and store needs to label a tshirt with a bunch of properties only relevant to the store) that forces us to have those properties. However, in your case, title and length are natural properties of your models. Every track actually does have a title and duration in reality. So does every Album and Video. Title and length describe the model, not the context. Therefore, just like you wouldn’t put an Article#body and Comment#body into a common table called “bodies” (just because both of them are texts called “body”), you shouldn’t join things just because they are similar in structure. They may differ in meaning. So I’d rather suggest having title and length columns in every table (videos, tracks, albums) and have some kind of polymorphic has_many through to glue it all together.Generally, look for reasons to simplify rather than complicate.
Hi,
This look exacly what I need ! But I am a bit confused about how the model is. there is a “product_property_id” field in Tee and Pen table ? the “id” field in Tee orPen is PK-FK ?
Thanks.
Nice job! Thanks a lot.
However, a small problem. Take your example. Let’s suppose Product has_and_belongs_to_many materials (not sure this is proper but I think you can get it). Then the current solution won’t find the materials attribute if we do Product.create(:materials = [...]). I don’t know what’s the term is for this kind of attribute…
I made an ugly fix for this by doing:
Is there any solution more elegant?
Thanks a lot for sharing this code! I’ve been interested in MTI in Rails for quite some time.
Is it possible to modify the code a little so that it supports something like:
@productproperties = ProductProperties.all @productproperties.each do |p| print p.tee.color end
This would be extremely useful. Thanks.
Bummer, nevermind. Just after posting the previous comment, I figured you can just do “p.sellable.color” and it’ll work fine. How dumb of me.
@hakunin
First, thank you so much, this is the best post I have ever seen about MTI on rails.
However, I had one problem when using :include.
Example: class Pen < ActiveRecord::Base include Sellable end
class Pack belongs_to :pen
named_scope :with_product_properties, :include => { :pen => { product_properties => title } end
So, if I try to use @pack = Pack.with_product_properties @pack.pen.title it says that title is an unknown property for this ‘aggregation however @pack.pen.product_properties.title is okay.
If you need more info, I could create a code to reproduce this error.
Thanks in advance!
I’m using a slightly different technique. I think it’s roughly similar, but it goes something like:
class Product < ActiveRecord::Base self.abstract_class = true has_one :product_properties, :as => :product, :dependent => :destroy delegate :price, :price=, :name, :name=, :description, :description=, :to => :product_properties def product_properties_with_autobuild product_properties_without_autobuild || build_product_properties end alias_method_chain :product_properties, :autobuild end
Then just inherit your products from Product.
This mostly works in rails 3, but isn’t perfect. I’ve been waiting for a decent CTI implementation for activerecord for years. I have a project that relies on it very heavily. Anyone know of an ORM that supports it properly? Can DataMapper do it?
I’ve been using the same pattern as Ron. I prefer using delegate over method_missing to avoid too much metamagic obviscation.
Would you be able to add which files the code would go in and their path in the rails directory structure? I am trying to recreate what you have done for my project and I cannot since when I try to ‘rake db:seed’ it tells me that acts_as_product is undefined. If I replace the call with ‘include Sellable’ I get ‘undefined method sellable_type=…’
I am new at this so any help you could give would be greatly appreciated.
Eric, I just had the same problem, and it was because my table wasn’t defined properly. the product_properties table must have at least the following columns:
id sellable_type sellable_id
Something that burned me a few times ago:
public_methods.include?(meth.to_s)
won’t work on 1.9 since method names would be returned as array of symbols instead of an array of strings
public_methods.map(&:to_sym).include?(meth.to_sym)
should work across different versions I think.
This has been extremely helpful to me. One issue I’ve got is that I can’t do eager loading with this. I get this error:
Can not eagerly load the polymorphic association :sellable
Would anyone know how to modify it so that we can do eager loading? I would like to reduce the N+1 queries. Thanks!
Hi, this is really a nice approach!
Did you thought about including dynamic finders ? If you just send them to the product_properties class you will get a product_properties object as return and not, as you may want, a pen or a tee object with all the necessary data. Maybe you have something in mind i haven’t thought of yet.
thanks anyway for your sharing.