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.
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).
class City < ActiveRecord::Base has_many :listings end
class Listing < ActiveRecord::Base belongs_to :city end
How would you generate the following URL to display listings by city:
Non-resource routes to the rescue. You can create a route that will hook these up as follows:
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:
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.