Close and Go BackBack to Viget

Using polymorphic_url to Generate URLs From Unknown Models

Clinton R. Nixon
Clinton R. Nixon, Senior Developer, March 15, 2008 0

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_#{@comment.id}"

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!

Name:

Email:

URL:

Not a robot? Prove it by entering the word below.


Remember my personal information

Notify me of follow-up comments?

A Development Community for Viget Labs and Beyond

Every team member here at Viget Labs strives to be an innovator. We members of the development team are no different - that's why we're constantly engaging in community discussions and exploring the unknown that is the next generation of open-source web applications.

Viget Is Hiring!

Viget has job openings for Ruby Developers, Interns, and Front-End Developers. Learn More »

Recent Comments

Smashing! Thanks for outlining what’s needed to be done so precisely :-)