Generate a path or URL string from an array of route components

Updated . Posted . Visible to the public.

When using form_for you can give the form's target URL either as a string or an array:

form_for(admin_user_path(@user)) do ... end
# same as:
form_for([:admin, @user]) do ... end

Same for link_to:

link_to("Label", edit_admin_user_path(@user))
# same as
link_to("Label", [:edit, :admin, @user])

polymorphic_path and polymorphic_url

If you would like to generate a path or URL string from an array of route components just as form_for does, you can use polymorphic_path or polymorphic_url:

polymorphic_url([:admin, @user]) # "/admin/users/55"

:action - Specifies the action prefix for the named route: :new or :edit. Default is no prefix.

polymorphic_url([@user, Post], :action => :new) # "/users/45/posts/new"
#same as
new_polymorphic_url([@user, Post]) # "/users/45/posts/new"

Namespacing of an ActiveRecord class nested in another is not supported

Assuming an architecture like this:

class Building < ActiveRecord::Base
end

class Building::Room < ActiveRecord::Base
  belongs_to :building
end

it won't be possible to guess the right path

building => #<Building id: 223, ... >
room => #<Building::Room id: 380, building_id: 223, ... >

polymorphic_path([room])
=> "/buildings/380/rooms/380/"  # <- wrong building id

polymorphic_path([building, room])
=>!! #<NoMethodError: undefined method `building_building_room_path' ...
Henning Koch
Last edit
Martin Straub
Keywords
rails, routing, router, url_for
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-10-20 10:17)