# URL Generation
Creating Paths and URLs from Objects
In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:
resources :magazines do resources :ads end
1
2
3When using
magazine_ad_path
, you can pass in instances ofMagazine
andAd
instead of the numeric IDs:<%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>
1You can also use
url_for
with a set of objects, and Rails will automatically determine which route you want:<%= link_to 'Ad details', url_for([@magazine, @ad]) %>
1For other actions, you just need to insert the action name as the first element of the array:
<%= link_to 'Edit Ad', [:edit, @magazine, @ad] %>
1Accessing Current URL
@full_path = request.url
1URLs for named routes
You can specify a name for any route using the
:as
option:get 'exit', to: 'sessions#destroy', as: :logout
1This will create
logout_path
andlogout_url
as named route helpers in your application. Callinglogout_path
will return/exit
URLs for resources routes
Creating a resourceful route will also expose a number of helpers to the controllers in your application.
resources :photos
1In the case of
resources :photos
:photos_path
returns/photos
new_photo_path
returns/photos/new
edit_photo_path(:id)
returns/photos/:id/edit
(for instance,edit_photo_path(10)
returns/photos/10/edit
)photo_path(:id)
returns/photos/:id
(for instance,photo_path(10)
returns/photos/10
)
Each of these helpers has a corresponding
_url
helper (such asphotos_url
) which returns the same path prefixed with the current host, port, and path prefix.