Skip to content


PolyPath … my first public plugin

I’ve run into the problem lately where I want to have resources that look like: http://host/users/1/photos/5 and http://hosts/events/1/photos/5. After some thought, I decided to put my solution into a plugin, so others wouldn’t have as a hard of time that I had.

<p>My solution is called PolyPath, which is just short for polymorphic paths.  Using a little trickery in defining your routes, and my controller and view helper, you can easily generate polymorphic routes.</p>


<p>As a proof of concept, I created a test website and created three resources using the scaffold_resource generator:</p>
1
2
3
4
5
6
7
8
9
10
11
class User < ActiveRecord::Base
  has_many :photos, :as => :photoable
end

class Event < ActiveRecord::Base
  has_many :photos, :as => :photoable
end

class Photo < ActiveRecord::Base
  belongs :to => :photoable, :polymorphic => true
end
<p>I then updated my routes to make everything fit together:</p>

map.resources :photos, :path_prefix => "/:photoable_type/:photoable_id"
<p>You can now have views that look like this:</p>
1
2
3
4
5
6
<p>
  <b>Subject:</b>
  <%=h @photo.subject %>
</p>

<%= link_to 'Edit', edit_photo_path(poly_path(@photo, :photoable)) %> |
<p>You can install the plugin by running</p>


<p>$ ruby script/plugin install http://smarticus.googlecode.com/svn/trunk/plugins/poly_path</p>


<p>If you think this plugin sucks, or if you want to know where my head was when I coded this this, either post a comment here or email me at <a href="mailto:bryan@osesm.com">bryan@osesm.com</a></p>

Posted in Uncategorized.