Polymorphic pathEvery now and then you might end up with something like the following route structure:
which inevitably leads to views like this:
resources :projects do resources :tasks do resources :documents end resources :users do resources :documents end end
It's pretty frustrating when you're trying to achieve logicless view nirvana.
- if @task = link_to 'Document' project_task_document_path(@project, @task, @document) - else = link_to 'Document', project_user_document_path(@project, @user, @document)
polymorphic_path. This little bit of Rails voodoo allows you to achieve the following with the above example:
But what if you want to do the same but with an edit action?
= link_to 'Document', polymorphic_path(@project, @task || @user, @document)
New and index actions get a little trickier but are still extremely simple
= link_to 'Edit Document', edit_polymorphic_path(@project, @task || @user, @document)
= link_to 'New Document', new_polymorphic_path(@project, @task || @user, :document) = link_to 'Documents', polymorphic_path(@project, @task || @user, :documents)
polymorphic_pathbuilds on the work in
polymorphic_urlwhich is just another component of the Rails framework. Methods such as
redirect_tomethods all utilise
polymorphic_urlto generate their paths.
If you find your view logic getting cluttered with if statements like the above, and you're willing to take a hit on the readability of your path in exchange for cleaner looking views or controller actions,
polymorphic_pathis your friend.
Post a Comment