How to Use the friendly_id gem w/ STI Models

To start off, the friendly_id gem allows your models to have “slugs” which ultimately help when you want your urls to appear more descriptive. For example instead of  you will get something like: .

It’s better for SEO and IMO provides a better experience for situations where someone copies a link and sends it to another individual.  When you see a descriptive URL you kind of know what to expect and it feels less threatening than ….. OR i’m just a wussy.

My current situation is this:
I have some STI models that use inheritance and want to use friendly_id with it.

The problem i ran into and erroneously thought was a bug can be found here: .  Basically when creating records for inheriting models i was getting duplicate slug errors.  Something like: “Error: Duplicate entry blah blah”.

A quick answer the gem’s author, Norman, rained light and joy on where i had gone wrong.

The Solution:

So how do you get STI models and friendly_id to work together?  This gist says it all and uses the idea of cars/brands as the STI model.  Note: this is really only for example, if you have a lot of cars and brands you will probably want to model that differently.

Read the docs:

The gem’s docs are really good.  While the docs for the FriendlyId::Scoped module explain everything in concise terms here they do not explicitly cover STI so hopefully this helps you out if you’re in the same situation.