resource
resource(*entities, &block)
public
Creates named routes for implementing verb-oriented controllers for a singleton resource. A singleton resource is global to its current context. For unnested singleton resources, the resource is global to the current user visiting the application, such as a user’s /account profile. For nested singleton resources, the resource is global to its parent resource, such as a projects resource that has_one :project_manager. The project_manager should be mapped as a singleton resource under projects:
map.resources :projects do |project| project.resource :project_manager end
See map.resources for general conventions. These are the main differences:
- A singular name is given to map.resource. The default controller name is still taken from the plural name.
- To specify a custom plural name, use the :plural option. There is no :singular option.
- No default index route is created for the singleton resource controller.
- When nesting singleton resources, only the singular name is used as the path prefix (example: ‘account/messages/1’)
For example:
map.resource :account
maps these actions in the Accounts controller:
class AccountsController < ActionController::Base # GET new_account_url def new # return an HTML form for describing the new account end # POST account_url def create # create an account end # GET account_url def show # find and return the account end # GET edit_account_url def edit # return an HTML form for editing the account end # PUT account_url def update # find and update the account end # DELETE account_url def destroy # delete the account end end
Along with the routes themselves, #resource generates named routes for use in controllers and views. map.resource :account produces these named routes and helpers:
Named Route Helpers ============ ============================================= account account_url, hash_for_account_url, account_path, hash_for_account_path new_account new_account_url, hash_for_new_account_url, new_account_path, hash_for_new_account_path edit_account edit_account_url, hash_for_edit_account_url, edit_account_path, hash_for_edit_account_path
Use the :as option for SEO friendly URLs
The :as option to map.resources can be used to generate SEO friendly URLs like so:
Code Example
map.resources :operating_systems, :as => 'operating-systems' # operating_systems_path => /operating-systems
Overview of all routes
To see all defined routes type in your console:
rake routes
This produces (eg.):
reorder_toolbox_items PUT /toolbox_items reord {:controller=>"toolbox_items", :action=>"reorder"} channels GET /channels {:controller=>"channels", :action=>"index"} ... etc.