Daniel Hoelbling-Inzko talks about programming

Explicit path helpers with STI in Rails

I am currently working on an application that makes use of Single-Table-Inheritance (STI) for some of it's models.

STI in Rails is quite simple, you simply subclass a model and add the type column to your table like this:

And the accompanying migration:

Now that that's out of the way, Rails url helpers will automagically use the right route depending on the class you feed to it's helpers. Here's an example:

You get the idea, rails helpers are smart about this. Only problem: How about the cases where you need an explicit helper like edit_person_path?

This is where it get's tricky:

Using the explicit helper rails will not do any STI magic and simply return the path you asked for. What I really needed was for a helper that points to /persons/:id/edit in case it's a Person record and to /students/:id/edit for students. After some digging (Rails STI isn't really the hottest topic on Google it seems) I found the polymorphic_path method that does exactly this:

Filed under rails, rails-2, ruby, ruby-2

My Photography business


dynamic css for .NET