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.
Brutuscat
Feb 15, 2012 @ 13:26:18
I think you are somehow confused… You should use nested resources: http://guides.rubyonrails.org/routing.html#nested-resources
class Magazine < ActiveRecord::Base
has_many :ads
end
class Ad < ActiveRecord::Base
belongs_to :magazine
end
resources :magazines do
resources :ads
end
/magazines/:id/ads
JR
Feb 23, 2012 @ 18:22:35
I agree Brutuscat. Nested resources are the way to go.
This was more an example for my of how you could manually create a URL a specific way if you didn’t like what rails gave you out of the box.
It’s something I figured out and wanted to record.
But I agree, nested is better and should be starting position.
Thanks for posting.
Eddie Lee
Oct 29, 2012 @ 01:30:35
Thanks for this! To avoid confusion though perhaps another example (such as creating a Settings page) would be more apt?
Eddie Lee
Oct 29, 2012 @ 01:31:14
Because this example seems perfect for nested resources.