Nesting resource routes with alternate scopes and keys + strong parameters.


DISCLAIMER:
This is a contrived example translated from a case where it actually made way more sense to break the familiar nested resource pattern. Also, I haven’t double-checked how Rails’ pluralization rules would affect the naming of any given Species.

Say you have a pair of models:

class Species
  # id
  # latin_name_with_underscores
end

class Animal
  # name
  # species_id
end

Normally, you’d nest resource routes in your routes.rb file something like:

resources :species do
  resources :animal
end

And your routes would look something like:

/species/:species_id/animals
/species/:species_id/animals/:animal_id

But… what if you wanted different nesting, resource ids, and route names?

namespace :latin_species do
  scope '/:latin_name' do
    resources :animals
  end
end

Now you have:

/latin_species/:latin_name/animals
/latin_species/:latin_name/animals/:id

In your controller app/latin_species/animals_controller.rb, you can now do the following to set the appropriate parent and child:

class LatinSpecies::AnimalsController < ApplicationController
  before_action :set_species_and_animal
#
#
#
  def set_species_and_animal
    @species = Species.find_by(latin_name_with_underscores: params[:latin_name])
    @animal = Animal.find(params[:id]) if pararms[:id]
  end
end

%d bloggers like this: