# 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
    3

    When using magazine_ad_path, you can pass in instances of Magazine  and Adinstead of the numeric IDs:

    <%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>
    
    1

    You can also use url_forwith a set of objects, and Rails will automatically determine which route you want:

    <%= link_to 'Ad details', url_for([@magazine, @ad]) %>
    
    1

    For other actions, you just need to insert the action name as the first element of the array:

    <%= link_to 'Edit Ad', [:edit, @magazine, @ad] %>
    
    1
  • Accessing Current URL

    @full_path = request.url
    
    1
  • URLs for named routes

    You can specify a name for any route using the :as option:

    get 'exit', to: 'sessions#destroy', as: :logout
    
    1

    This will create logout_pathand logout_urlas named route helpers in your application. Calling logout_pathwill 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
    
    1

    In 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 as photos_url) which returns the same path prefixed with the current host, port, and path prefix.