← Back to Upcase

Nested routes help

(Scott Hollinshead) #1

This is my routes file currently:

Aas::Application.routes.draw do
  root "companies#index"
  resources :companies, only: :index do
    resources :job_sheets

This makes my routes look like this:

new_company_job_sheet GET    /companies/:company_id/job_sheets/new(.:format)      job_sheets#new

Is there a way of getting hte url to show the company name instead of /companies/


(Matthew Sumner) #2

Do you want the company name to appear in the /companies/ part of the url or the /:company_id/ part?

I presume the intention is to have more relevant url’s in your app. By far the easiest way is to modify a model by overriding the to_param method. When Rails wants to represent a model in the url it calls to_param. We can override this to include the company name:

class Company < ActiveRecord::Base
  def to_param

We call .parameterize to ensure the name is url friendly. Now when you visit a company page it will show the name (e.g. /companies/1-thoughtbot/). By keeping the id in the url we don’t need to make any changes to how rails retrieves the company record. In the controller when we call Company.find(params[:id]) ActiveRecord will call to_int on it to convert into an integer. This is why it’s necessary to have the id at the start of this part of the URL.

If you don’t want the id’s showing then you’ll need to get more advance. I’d highly recommend checking out Rails Casts. One of the episodes available to subscribers is on this very topic

(David Briggs) #3

Friendly_id is a gem that can help with the more advanced id replacement: https://github.com/norman/friendly_id

RailsCasts also made an episode for firendly_id: http://railscasts.com/episodes/314-pretty-urls-with-friendlyid