Monday, January 21, 2008

STI Views Revisited or Polymorphic Paths

In my previous post I lamented the strange and inconsistent behavior of the the automatically generated view for a simple STI hierarchy. After many searches and several futile attempts to explain myself on the #rubyonrails IRC chat, I posted my question (slightly simplified) to the Ruby on Rails: Core list.

Mislav Marohnić was kind enough to shed light on my problem. He said (edited for context):

When you say link_to(text, record), a polymorphic url is constructed depending on the model. But when you say edit_parent_path, you are explicitly stating that you are dealing with Parent records and that no polymorphism should take place.

I understand that when using STI you have a need for a polymorphic helper, but I don't think changing the behavior of named routes (explicit or automatically generated) is a solution - it would just be the source of more confusion for others.

Your cup of tea would be the edit_polymorphic_path helper...
Essentially, I just need to change:
link_to 'Edit', edit_parent_path(parent)
link_to 'Edit', edit_polymorphic_path(parent)
and edit_polymorphic_path() will do the correct thing and generate the path based on the concrete record type.

Problem solved! Thank you Mislav!

On a side note, edit_polymorphic_path() used to be part of the simply_helpful plugin, but had been merged into core Rails more than 8 months ago. However it had not been documented, and my post seems to have sparked the documentation and exposure of this module and its kin. Excellent! My minor and indirect contribution to Rails. ... and, you won't read this in any Rails book!

If you found this post helpful, or you have more thought on this subject, please leave a message in the comments. If you want to read more about my exploration of polymorphism and STI on Rails, subscribe to the blog feed and stay updated.


Topher said...

Thanks for this post! I am planning on using STI and your series of posts will be referenced many times I'm sure.

A.S. said...

Thanks Topher, and good luck!