polymorphic_url
polymorphic_url(record_or_hash_or_array, options = {})Constructs a call to a named RESTful route for the given record and returns the resulting URL string. For example:
polymorphic_url(post) # calls post_url(post) #=> "http://example.com/posts/1"
Options
- :action — specifies the action prefix for the named route: :new, :edit or :formatted. Default is no prefix.
- :routing_type — :path or :url (default :url).
Examples
# an Article record polymorphic_url(record) #-> article_url(record) # a Comment record polymorphic_url(record) #-> comment_url(record) # it recognizes new records and maps to the collection record = Comment.new polymorphic_url(record) #-> comments_url()
3Notes
Universal partial
polymorphic_url is very useful if you want to create an universal partial that works for more than 1 type of object passed to it.
For example in you sidebar you might have a _sidebar.html.erb partial that's supposed to display links to "Edit" and "Delete" actions. You can write it in such a way that it can be reused for different types of objects (in the example below we pass either a Post or a Note).
your_template.html.erb <%= render :partial => 'shared/sidebar', :locals => { :obj => Post.new -%>
other_template.html.erb <%= render :partial => 'shared/sidebar', :locals => { :obj => Note.new -%>
_sidebar.html.erb <%= link_to "Edit", polymorhpic_url(obj, :action => 'edit') -%> <%= link_to "Delete", polymorphic_url(obj), :method => :delete -%>
Easier Universal Partials
@hosiawak provides a great example of how to use polymorphic_path to produce universal partials. You can actually simply his example even more with the following:
<%= link_to 'Edit', edit_polymorphic_path(obj) %> <%= link_to 'Delete', obj, :method => :delete %>
So the things to note are that in addition to polymorphic_path, Rails also provides an "edit_" version just like on your resources so you can use that instead of specifying the action specifically. The second thing to remember is if you pass just the raw object as the path then then rails will automatically wrap it in a call to polymorphic_path.
Anchor option
It's not documented, but :anchor is an option.
polymorphic_path(commentable, :anchor => 'comments')
will return:
/article/1#comments