Nested routes help

This is my routes file currently:

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

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/

Thanks

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
    "#{id}-#{name}".parameterize
  end
end

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

1 Like

Friendly_id is a gem that can help with the more advanced id replacement: GitHub - norman/friendly_id: FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for ActiveRecord. It allows you to create pretty URL’s and work with human-friendly strings as if they were numeric ids for ActiveRecord models.

RailsCasts also made an episode for firendly_id: #314 Pretty URLs with FriendlyId - RailsCasts