Polymorphic URL feature in Rails 2.0

I just found a wonderful feature in Rails 2.1 (although was added in 2.0).

There is a new function called polymorphic_url that will generate the correct URL for a descendant model class when using single table inheritance. You can find the documentation here.

For our example let’s assume that we have a Party model with descendant models of Person and Organization. In addition, please assume that the controllers confirm to RESTful practices. Also assume that we do not allow creation of parties through the parties#new parties#create actions. The user must create parties through the more specific people#new and people#create actions and organizations through its respective actions.

If you allow the user to browse to a parties index, then you will be faced with a situation. Should you simply create a show and edit that will navigate to parties#show and parties#edit respectively. That is valid solution to this problem, but a limiting solution for your users

I would suggest that each index entry’s show and edit links take the user to the correct new action of its model type. So, a person entry’s show link should navigate to the person#show action, etc…

To accomplish this, simply employ the power of the polymorphic_url helper.

1
2
3
4
5
# change this
party_path( @party )

# to this
edit_polymorphic_path( @party )

Leave a Reply