v2.1.0 - Show latest stable - 2 notes - Class: ActionController::Resources
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

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

    # POST account_url
    def create
      # create an account

    # GET account_url
    def show
      # find and return the account

    # GET edit_account_url
    def edit
      # return an HTML form for editing the account

    # PUT account_url
    def update
      # find and update the account

    # DELETE account_url
    def destroy
      # delete the account

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
Show source
Register or log in to add new notes.
June 29, 2008
9 thanks

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
August 12, 2008
1 thank

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"}