When you define a new resource in rails, you get a slew of routes automatically generated for you, defined by a resource definition in your routes file.

routes.rb

 resources :photos

Now this is great for general resources. But what if you need a URL, that can’t be defined by the conventional rails route.

For example what if you need to display listings (a resource) by cities (another resource).

city.rb

class City < ActiveRecord::Base
  has_many  :listings
end

Listing.rb

class Listing < ActiveRecord::Base
  belongs_to  :city
end

How would you generate the following URL to display listings by city:

/cities/1/listings

Non-resource routes to the rescue. You can create a route that will hook these up as follows:

routes.rb

  match '/cities(/:id(/listings))',  :to => 'cities#listings'

Now whenever rails sees a request of this type, it will forward it as follows:

:controller => citities
:id => params[:id]
:action -> listings

Which ends up in:

cities_controller.rb

class CitiesController < ApplicationController
  def listings
    @listings = Listing.where(:city_id => params[:id])
  end
end

For more on non-resource rails routes checkout the excellent documentation at the Ruby On Rails Guide.

About these ads