Ruby on Rails: Restful Links When You Don’t Know the Class

by Charles Max Wood on July 21, 2009

I had a friend email me a week or so ago about generating a link from your restful routes when you don’t know the class. Here’s a quick thumbnail of the scenario.

You have a bunch of restful routes like these:

map.resources :users
map.resources :groups

And you have a model that has a polymorphic association, meaning that it has an associated value that can be from more than one model. Here’s an example of how that’s done.

class Post  true

class User  :o wner

class Group
  has_many :posts, :as => :o wner

Now, let’s say that when you show a post, you want to provide a link to the owner of the post when you display it on its show page. You know that because you’ve provided the restful routes in your config/routes.rb file as show above, you get the nice functionality of the user_path and the group_path methods. The problem is that because you don’t know if @post.owner is a user or a group.

You could conditionally call one of the methods:


That’s a little messy, but it works. The solution I suggested was a little more elegant, but still a little messy:


It removed the conditionals, but it’s not very clear to read. It turns out that he found a solution already baked into Ruby on Rails:


You can find documentation on the polymorphic_path method on RailsBrain.

You’ll find that polymorphic_path also supports other forms of the path helpers such as edit_polymorphic_path, new_polymorphic_path, and formatted_polymorphic_path.

I also got information from

  • Philippe Creux

    We followed the same process starting with something dirty and ending up on something clean. I think you might even remove the call to ‘polymorphic_path’.

    link_to, @post.owner should work as well. :)

  • Srikanth

    Great Article.
    Thanks :)

Previous post:

Next post: