Rails : Routes : Difference between resource and resources in routes.rb

Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code.

If you need to create routes for more than one resource, you can save a bit of typing by defining them all with a single call to resources:

resources :photos, :books, :videos

This works exactly the same as:

resources :photos
resources :books
resources :videos

Singular Resources

Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like /profile to always show the profile of the currently logged in user.

Or, Normally your currently logged-In user belongs to a single organization, so to goto his/her organization profile page there can be two routes

#1
/organizations/:id

#2
/organization #simply

Here, the later implementation makes more sense; isnot it? you get the organization object from association

# in organizations#show
@organization = current_user.organization

To define such singular resource you use resource method: Example

# in routes.rb
resource :organization

creates six different routes in your application, all mapping to the Organizations controller:

enter image description here

whereas, you define plural resources using resources method

resources :organizations

enter image description here

This resourceful route:
resource :geocoder

A long-standing bug prevents form_for from working automatically with singular resources. As a workaround, specify the URL for the form directly, like so:

form_for @geocoder, url: geocoder_path do|f|

Conflicts with Naming conventions

# in routes.rb
resources :people
resources :person

$ rake routes | grep person
person_index GET      /person(.:format)                      person#index
$ rake routes | grep people
      people GET      /people(.:format)                      people#index

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s