Using polymorphic_url to Generate URLs From Unknown Models

Clinton R. Dreisbach, Former Viget

Article Category: #Code

Posted on

I was recently helping out another developer with a polymorphic "commentable" model; that is, comments polymorphically belonged to any model as "commentables." In most web applications, comment forms are shown on their parent, like the comment form shown when looking at this post. After we created a comment, we wanted to redirect back to the commentable resource, even though we don't know what class it is. With Rails 2.0's polymorphic routes, it's a pretty easy task. You can just pass the model to redirect_to, like so:
redirect_to @commentable 
We wanted to add an anchor, though, to take you to the comment you just added. After struggling with it for a bit, I found polymorphic_url deep in ActionController. This method is in the Rails documentation, but I'd never seen it before. It returns the URL for an ActiveRecord model as a string, so you can do something like the following:
redirect_to polymorphic_url(@commentable) + "#comment_#{}" 
It's not particularly pretty, but it gets the job done. I'd love to see a better way. If you have one, let us know in the comments!

Related Articles