ASP.NET MVC vs Rails Routes

Leave a comment

One thing I have always wanted to compare are the default routes you get with Rails, with the default routes you get with ASP.NET MVC.

Rails

rails-routes

ASP.NET MVC4

GET /Permits Index
GET /Permits/Create Create
POST /Permits/Create Create
GET /Permits/Details/1 Details
GET /Permits/Edit/5 Edit
POST /Permits/Edit/5 Edit
GET /Permits/Delete/5 Delete
POST /Permits/Delete/5

Pretty close. Biggest differences are Rails does

/photos/:id/edit

for editing a resource while ASP.NET MVC does

/Permits/Edit/5

And some of the action names are different (new/create, show/details, update/edit, destroy/delete).

Of course you can always change your routing logic in ASP.NET MVC if you want something closer to what they do it in Rails:

http://stackoverflow.com/questions/9332026/asp-net-mvc-4-route-news-5

Anyways. Just something I have always wanted look at and compare.

Non-resource routes in rails

4 Comments

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.

%d bloggers like this: