Read more

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

Henning Koch
October 20, 2010Software engineer at makandra GmbH

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
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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' ...
Posted by Henning Koch to makandra dev (2010-10-20 12:17)