1 module ActionController
4 # ActionController::Resources are a way of defining RESTful \resources. A RESTful \resource, in basic terms,
5 # is something that can be pointed at and it will respond with a representation of the data requested.
6 # In real terms this could mean a user with a browser requests an HTML page, or that a desktop application
9 # RESTful design is based on the assumption that there are four generic verbs that a user of an
10 # application can request from a \resource (the noun).
12 # \Resources can be requested using four basic HTTP verbs (GET, POST, PUT, DELETE), the method used
13 # denotes the type of action that should take place.
15 # === The Different Methods and their Usage
17 # * GET - Requests for a \resource, no saving or editing of a \resource should occur in a GET request.
18 # * POST - Creation of \resources.
19 # * PUT - Editing of attributes on a \resource.
20 # * DELETE - Deletion of a \resource.
24 # # A GET request on the Posts resource is asking for all Posts
27 # # A GET request on a single Post resource is asking for that particular Post
30 # # A POST request on the Posts resource is asking for a Post to be created with the supplied details
31 # POST /posts # with => { :post => { :title => "My Whizzy New Post", :body => "I've got a brand new combine harvester" } }
33 # # A PUT request on a single Post resource is asking for a Post to be updated
34 # PUT /posts # with => { :id => 1, :post => { :title => "Changed Whizzy Title" } }
36 # # A DELETE request on a single Post resource is asking for it to be deleted
37 # DELETE /posts # with => { :id => 1 }
39 # By using the REST convention, users of our application can assume certain things about how the data
40 # is requested and how it is returned. Rails simplifies the routing part of RESTful design by
41 # supplying you with methods to create them in your routes.rb file.
43 # Read more about REST at http://en.wikipedia.org/wiki/Representational_State_Transfer
45 INHERITABLE_OPTIONS
= :namespace, :shallow, :actions
47 class Resource
#:nodoc:
48 DEFAULT_ACTIONS
= :index, :create, :new, :edit, :show, :update, :destroy
50 attr_reader
:collection_methods, :member_methods, :new_methods
51 attr_reader
:path_prefix, :name_prefix, :path_segment
52 attr_reader
:plural, :singular
55 def initialize(entities
, options
)
57 @singular ||= options
[:singular] || plural
.to_s
.singularize
58 @path_segment = options
.delete(:as) || @plural
69 @controller ||= "#{options[:namespace]}#{(options[:controller] || plural).to_s}"
72 def requirements(with_id
= false)
73 @requirements ||= @options[:requirements] || {}
74 @id_requirement ||= { :id => @requirements.delete(:id) || /[^#{Routing::SEPARATORS.join}]+/ }
76 with_id
? @requirements.merge(@id_requirement) : @requirements
80 @conditions ||= @options[:conditions] || {}
84 @path ||= "#{path_prefix}/#{path_segment}"
88 new_action
= self.options
[:path_names][:new] if self.options
[:path_names]
89 new_action
||= Base
.resources_path_names
[:new]
90 @new_path ||= "#{path}/#{new_action}"
93 def shallow_path_prefix
94 @shallow_path_prefix ||= "#{path_prefix unless @options[:shallow]}"
98 @member_path ||= "#{shallow_path_prefix}/#{path_segment}/:id"
101 def nesting_path_prefix
102 @nesting_path_prefix ||= "#{shallow_path_prefix}/#{path_segment}/:#{singular}_id"
105 def shallow_name_prefix
106 @shallow_name_prefix ||= "#{name_prefix unless @options[:shallow]}"
109 def nesting_name_prefix
110 "#{shallow_name_prefix}#{singular}_"
114 @action_separator ||= Base
.resource_action_separator
118 @singular.to_s
== @plural.to_s
121 def has_action
?(action
)
122 !DEFAULT_ACTIONS
.include?(action
) || @options[:actions].nil? || @options[:actions].include?(action
)
127 @collection_methods = arrange_actions_by_methods(options
.delete(:collection))
128 @member_methods = arrange_actions_by_methods(options
.delete(:member))
129 @new_methods = arrange_actions_by_methods(options
.delete(:new))
132 def add_default_actions
133 add_default_action(member_methods
, :get, :edit)
134 add_default_action(new_methods
, :get, :new)
137 def set_allowed_actions
138 only
= @options.delete(:only)
139 except
= @options.delete(:except)
142 raise ArgumentError
, 'Please supply either :only or :except, not both.'
143 elsif only
== :all || except
== :none
144 options
[:actions] = DEFAULT_ACTIONS
145 elsif only
== :none || except
== :all
146 options
[:actions] = []
148 options
[:actions] = DEFAULT_ACTIONS
& Array(only
).map(&:to_sym)
150 options
[:actions] = DEFAULT_ACTIONS
- Array(except
).map(&:to_sym)
152 # leave options[:actions] alone
157 @path_prefix = options
.delete(:path_prefix)
158 @name_prefix = options
.delete(:name_prefix)
161 def arrange_actions_by_methods(actions
)
162 (actions
|| {}).inject({}) do |flipped_hash
, (key
, value
)|
163 (flipped_hash
[value
] ||= []) << key
168 def add_default_action(collection
, method
, action
)
169 (collection
[method
] ||= []).unshift(action
)
173 class SingletonResource
< Resource
#:nodoc:
174 def initialize(entity
, options
)
175 @singular = @plural = entity
176 options
[:controller] ||= @singular.to_s
.pluralize
180 alias_method
:shallow_path_prefix, :path_prefix
181 alias_method
:shallow_name_prefix, :name_prefix
182 alias_method
:member_path, :path
183 alias_method
:nesting_path_prefix, :path
186 # Creates named routes for implementing verb-oriented controllers
187 # for a collection \resource.
191 # map.resources :messages
193 # will map the following actions in the corresponding controller:
195 # class MessagesController < ActionController::Base
198 # # return all messages
201 # # GET new_message_url
203 # # return an HTML form for describing a new message
206 # # POST messages_url
208 # # create a new message
211 # # GET message_url(:id => 1)
213 # # find and return a specific message
216 # # GET edit_message_url(:id => 1)
218 # # return an HTML form for editing a specific message
221 # # PUT message_url(:id => 1)
223 # # find and update a specific message
226 # # DELETE message_url(:id => 1)
228 # # delete a specific message
232 # Along with the routes themselves, +resources+ generates named routes for use in
233 # controllers and views. <tt>map.resources :messages</tt> produces the following named routes and helpers:
235 # Named Route Helpers
236 # ============ =====================================================
237 # messages messages_url, hash_for_messages_url,
238 # messages_path, hash_for_messages_path
240 # message message_url(id), hash_for_message_url(id),
241 # message_path(id), hash_for_message_path(id)
243 # new_message new_message_url, hash_for_new_message_url,
244 # new_message_path, hash_for_new_message_path
246 # edit_message edit_message_url(id), hash_for_edit_message_url(id),
247 # edit_message_path(id), hash_for_edit_message_path(id)
249 # You can use these helpers instead of +url_for+ or methods that take +url_for+ parameters. For example:
251 # redirect_to :controller => 'messages', :action => 'index'
253 # <%= link_to "edit this message", :controller => 'messages', :action => 'edit', :id => @message.id %>
257 # redirect_to messages_url
259 # <%= link_to "edit this message", edit_message_url(@message) # calls @message.id automatically
261 # Since web browsers don't support the PUT and DELETE verbs, you will need to add a parameter '_method' to your
262 # form tags. The form helpers make this a little easier. For an update form with a <tt>@message</tt> object:
264 # <%= form_tag message_path(@message), :method => :put %>
268 # <% form_for :message, @message, :url => message_path(@message), :html => {:method => :put} do |f| %>
272 # <% form_for @message do |f| %>
274 # which takes into account whether <tt>@message</tt> is a new record or not and generates the
275 # path and method accordingly.
277 # The +resources+ method accepts the following options to customize the resulting routes:
278 # * <tt>:collection</tt> - Add named routes for other actions that operate on the collection.
279 # Takes a hash of <tt>#{action} => #{method}</tt>, where method is <tt>:get</tt>/<tt>:post</tt>/<tt>:put</tt>/<tt>:delete</tt>,
280 # an array of any of the previous, or <tt>:any</tt> if the method does not matter.
281 # These routes map to a URL like /messages/rss, with a route of +rss_messages_url+.
282 # * <tt>:member</tt> - Same as <tt>:collection</tt>, but for actions that operate on a specific member.
283 # * <tt>:new</tt> - Same as <tt>:collection</tt>, but for actions that operate on the new \resource action.
284 # * <tt>:controller</tt> - Specify the controller name for the routes.
285 # * <tt>:singular</tt> - Specify the singular name used in the member routes.
286 # * <tt>:requirements</tt> - Set custom routing parameter requirements.
287 # * <tt>:conditions</tt> - Specify custom routing recognition conditions. \Resources sets the <tt>:method</tt> value for the method-specific routes.
288 # * <tt>:as</tt> - Specify a different \resource name to use in the URL path. For example:
289 # # products_path == '/productos'
290 # map.resources :products, :as => 'productos' do |product|
291 # # product_reviews_path(product) == '/productos/1234/comentarios'
292 # product.resources :product_reviews, :as => 'comentarios'
295 # * <tt>:has_one</tt> - Specify nested \resources, this is a shorthand for mapping singleton \resources beneath the current.
296 # * <tt>:has_many</tt> - Same has <tt>:has_one</tt>, but for plural \resources.
298 # You may directly specify the routing association with +has_one+ and +has_many+ like:
300 # map.resources :notes, :has_one => :author, :has_many => [:comments, :attachments]
302 # This is the same as:
304 # map.resources :notes do |notes|
305 # notes.resource :author
306 # notes.resources :comments
307 # notes.resources :attachments
310 # * <tt>:path_names</tt> - Specify different names for the 'new' and 'edit' actions. For example:
311 # # new_products_path == '/productos/nuevo'
312 # map.resources :products, :as => 'productos', :path_names => { :new => 'nuevo', :edit => 'editar' }
314 # You can also set default action names from an environment, like this:
315 # config.action_controller.resources_path_names = { :new => 'nuevo', :edit => 'editar' }
317 # * <tt>:path_prefix</tt> - Set a prefix to the routes with required route variables.
319 # Weblog comments usually belong to a post, so you might use +resources+ like:
321 # map.resources :articles
322 # map.resources :comments, :path_prefix => '/articles/:article_id'
324 # You can nest +resources+ calls to set this automatically:
326 # map.resources :articles do |article|
327 # article.resources :comments
330 # The comment \resources work the same, but must now include a value for <tt>:article_id</tt>.
332 # article_comments_url(@article)
333 # article_comment_url(@article, @comment)
335 # article_comments_url(:article_id => @article)
336 # article_comment_url(:article_id => @article, :id => @comment)
338 # If you don't want to load all objects from the database you might want to use the <tt>article_id</tt> directly:
340 # articles_comments_url(@comment.article_id, @comment)
342 # * <tt>:name_prefix</tt> - Define a prefix for all generated routes, usually ending in an underscore.
343 # Use this if you have named routes that may clash.
345 # map.resources :tags, :path_prefix => '/books/:book_id', :name_prefix => 'book_'
346 # map.resources :tags, :path_prefix => '/toys/:toy_id', :name_prefix => 'toy_'
348 # You may also use <tt>:name_prefix</tt> to override the generic named routes in a nested \resource:
350 # map.resources :articles do |article|
351 # article.resources :comments, :name_prefix => nil
354 # This will yield named \resources like so:
356 # comments_url(@article)
357 # comment_url(@article, @comment)
359 # * <tt>:shallow</tt> - If true, paths for nested resources which reference a specific member
360 # (ie. those with an :id parameter) will not use the parent path prefix or name prefix.
362 # The <tt>:shallow</tt> option is inherited by any nested resource(s).
364 # For example, 'users', 'posts' and 'comments' all use shallow paths with the following nested resources:
366 # map.resources :users, :shallow => true do |user|
367 # user.resources :posts do |post|
368 # post.resources :comments
371 # # --> GET /users/1/posts (maps to the PostsController#index action as usual)
372 # # also adds the usual named route called "user_posts"
373 # # --> GET /posts/2 (maps to the PostsController#show action as if it were not nested)
374 # # also adds the named route called "post"
375 # # --> GET /posts/2/comments (maps to the CommentsController#index action)
376 # # also adds the named route called "post_comments"
377 # # --> GET /comments/2 (maps to the CommentsController#show action as if it were not nested)
378 # # also adds the named route called "comment"
380 # You may also use <tt>:shallow</tt> in combination with the +has_one+ and +has_many+ shorthand notations like:
382 # map.resources :users, :has_many => { :posts => :comments }, :shallow => true
384 # * <tt>:only</tt> and <tt>:except</tt> - Specify which of the seven default actions should be routed to.
386 # <tt>:only</tt> and <tt>:except</tt> may be set to <tt>:all</tt>, <tt>:none</tt>, an action name or a
387 # list of action names. By default, routes are generated for all seven actions.
391 # map.resources :posts, :only => [:index, :show] do |post|
392 # post.resources :comments, :except => [:update, :destroy]
394 # # --> GET /posts (maps to the PostsController#index action)
395 # # --> POST /posts (fails)
396 # # --> GET /posts/1 (maps to the PostsController#show action)
397 # # --> DELETE /posts/1 (fails)
398 # # --> POST /posts/1/comments (maps to the CommentsController#create action)
399 # # --> PUT /posts/1/comments/1 (fails)
401 # The <tt>:only</tt> and <tt>:except</tt> options are inherited by any nested resource(s).
403 # If <tt>map.resources</tt> is called with multiple resources, they all get the same options applied.
407 # map.resources :messages, :path_prefix => "/thread/:thread_id"
408 # # --> GET /thread/7/messages/1
410 # map.resources :messages, :collection => { :rss => :get }
411 # # --> GET /messages/rss (maps to the #rss action)
412 # # also adds a named route called "rss_messages"
414 # map.resources :messages, :member => { :mark => :post }
415 # # --> POST /messages/1/mark (maps to the #mark action)
416 # # also adds a named route called "mark_message"
418 # map.resources :messages, :new => { :preview => :post }
419 # # --> POST /messages/new/preview (maps to the #preview action)
420 # # also adds a named route called "preview_new_message"
422 # map.resources :messages, :new => { :new => :any, :preview => :post }
423 # # --> POST /messages/new/preview (maps to the #preview action)
424 # # also adds a named route called "preview_new_message"
425 # # --> /messages/new can be invoked via any request method
427 # map.resources :messages, :controller => "categories",
428 # :path_prefix => "/category/:category_id",
429 # :name_prefix => "category_"
430 # # --> GET /categories/7/messages/1
431 # # has named route "category_message"
433 # The +resources+ method sets HTTP method restrictions on the routes it generates. For example, making an
434 # HTTP POST on <tt>new_message_url</tt> will raise a RoutingError exception. The default route in
435 # <tt>config/routes.rb</tt> overrides this and allows invalid HTTP methods for \resource routes.
436 def resources(*entities
, &block
)
437 options
= entities
.extract_options
!
438 entities
.each
{ |entity
| map_resource(entity
, options
.dup
, &block
) }
441 # Creates named routes for implementing verb-oriented controllers for a singleton \resource.
442 # A singleton \resource is global to its current context. For unnested singleton \resources,
443 # the \resource is global to the current user visiting the application, such as a user's
444 # <tt>/account</tt> profile. For nested singleton \resources, the \resource is global to its parent
445 # \resource, such as a <tt>projects</tt> \resource that <tt>has_one :project_manager</tt>.
446 # The <tt>project_manager</tt> should be mapped as a singleton \resource under <tt>projects</tt>:
448 # map.resources :projects do |project|
449 # project.resource :project_manager
452 # See +resources+ for general conventions. These are the main differences:
453 # * A singular name is given to <tt>map.resource</tt>. The default controller name is still taken from the plural name.
454 # * To specify a custom plural name, use the <tt>:plural</tt> option. There is no <tt>:singular</tt> option.
455 # * No default index route is created for the singleton \resource controller.
456 # * When nesting singleton \resources, only the singular name is used as the path prefix (example: 'account/messages/1')
460 # map.resource :account
462 # maps these actions in the Accounts controller:
464 # class AccountsController < ActionController::Base
465 # # GET new_account_url
467 # # return an HTML form for describing the new account
472 # # create an account
477 # # find and return the account
480 # # GET edit_account_url
482 # # return an HTML form for editing the account
487 # # find and update the account
490 # # DELETE account_url
492 # # delete the account
496 # Along with the routes themselves, +resource+ generates named routes for
497 # use in controllers and views. <tt>map.resource :account</tt> produces
498 # these named routes and helpers:
500 # Named Route Helpers
501 # ============ =============================================
502 # account account_url, hash_for_account_url,
503 # account_path, hash_for_account_path
505 # new_account new_account_url, hash_for_new_account_url,
506 # new_account_path, hash_for_new_account_path
508 # edit_account edit_account_url, hash_for_edit_account_url,
509 # edit_account_path, hash_for_edit_account_path
510 def resource(*entities
, &block
)
511 options
= entities
.extract_options
!
512 entities
.each
{ |entity
| map_singleton_resource(entity
, options
.dup
, &block
) }
516 def map_resource(entities
, options
= {}, &block
)
517 resource
= Resource
.new(entities
, options
)
519 with_options
:controller => resource
.controller
do |map
|
520 map_collection_actions(map
, resource
)
521 map_default_collection_actions(map
, resource
)
522 map_new_actions(map
, resource
)
523 map_member_actions(map
, resource
)
525 map_associations(resource
, options
)
528 with_options(options
.slice(*INHERITABLE_OPTIONS
).merge(:path_prefix => resource
.nesting_path_prefix
, :name_prefix => resource
.nesting_name_prefix
), &block
)
533 def map_singleton_resource(entities
, options
= {}, &block
)
534 resource
= SingletonResource
.new(entities
, options
)
536 with_options
:controller => resource
.controller
do |map
|
537 map_collection_actions(map
, resource
)
538 map_default_singleton_actions(map
, resource
)
539 map_new_actions(map
, resource
)
540 map_member_actions(map
, resource
)
542 map_associations(resource
, options
)
545 with_options(options
.slice(*INHERITABLE_OPTIONS
).merge(:path_prefix => resource
.nesting_path_prefix
, :name_prefix => resource
.nesting_name_prefix
), &block
)
550 def map_associations(resource
, options
)
551 map_has_many_associations(resource
, options
.delete(:has_many), options
) if options
[:has_many]
553 path_prefix
= "#{options.delete(:path_prefix)}#{resource.nesting_path_prefix}"
554 name_prefix
= "#{options.delete(:name_prefix)}#{resource.nesting_name_prefix}"
556 Array(options
[:has_one]).each
do |association
|
557 resource(association
, options
.slice(*INHERITABLE_OPTIONS
).merge(:path_prefix => path_prefix
, :name_prefix => name_prefix
))
561 def map_has_many_associations(resource
, associations
, options
)
564 associations
.each
do |association
,has_many
|
565 map_has_many_associations(resource
, association
, options
.merge(:has_many => has_many
))
568 associations
.each
do |association
|
569 map_has_many_associations(resource
, association
, options
)
572 resources(associations
, options
.slice(*INHERITABLE_OPTIONS
).merge(:path_prefix => resource
.nesting_path_prefix
, :name_prefix => resource
.nesting_name_prefix
, :has_many => options
[:has_many]))
577 def map_collection_actions(map
, resource
)
578 resource
.collection_methods
.each
do |method
, actions
|
579 actions
.each
do |action
|
580 [method
].flatten
.each
do |m
|
581 map_resource_routes(map
, resource
, action
, "#{resource.path}#{resource.action_separator}#{action}", "#{action}_#{resource.name_prefix}#{resource.plural}", m
)
587 def map_default_collection_actions(map
, resource
)
588 index_route_name
= "#{resource.name_prefix}#{resource.plural}"
590 if resource
.uncountable
?
591 index_route_name
<< "_index"
594 map_resource_routes(map
, resource
, :index, resource
.path
, index_route_name
)
595 map_resource_routes(map
, resource
, :create, resource
.path
, index_route_name
)
598 def map_default_singleton_actions(map
, resource
)
599 map_resource_routes(map
, resource
, :create, resource
.path
, "#{resource.shallow_name_prefix}#{resource.singular}")
602 def map_new_actions(map
, resource
)
603 resource
.new_methods
.each
do |method
, actions
|
604 actions
.each
do |action
|
605 route_path
= resource
.new_path
606 route_name
= "new_#{resource.name_prefix}#{resource.singular}"
608 unless action
== :new
609 route_path
= "#{route_path}#{resource.action_separator}#{action}"
610 route_name
= "#{action}_#{route_name}"
613 map_resource_routes(map
, resource
, action
, route_path
, route_name
, method
)
618 def map_member_actions(map
, resource
)
619 resource
.member_methods
.each
do |method
, actions
|
620 actions
.each
do |action
|
621 [method
].flatten
.each
do |m
|
622 action_path
= resource
.options
[:path_names][action
] if resource
.options
[:path_names].is_a
?(Hash
)
623 action_path
||= Base
.resources_path_names
[action
] || action
625 map_resource_routes(map
, resource
, action
, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m
)
630 route_path
= "#{resource.shallow_name_prefix}#{resource.singular}"
631 map_resource_routes(map
, resource
, :show, resource
.member_path
, route_path
)
632 map_resource_routes(map
, resource
, :update, resource
.member_path
, route_path
)
633 map_resource_routes(map
, resource
, :destroy, resource
.member_path
, route_path
)
636 def map_resource_routes(map
, resource
, action
, route_path
, route_name
= nil, method
= nil)
637 if resource
.has_action
?(action
)
638 action_options
= action_options_for(action
, resource
, method
)
639 formatted_route_path
= "#{route_path}.:format"
641 if route_name
&& @set.named_routes
[route_name
.to_sym
].nil?
642 map
.named_route(route_name
, route_path
, action_options
)
643 map
.named_route("formatted_#{route_name}", formatted_route_path
, action_options
)
645 map
.connect(route_path
, action_options
)
646 map
.connect(formatted_route_path
, action_options
)
651 def add_conditions_for(conditions
, method
)
652 returning({:conditions => conditions
.dup
}) do |options
|
653 options
[:conditions][:method] = method
unless method
== :any
657 def action_options_for(action
, resource
, method
= nil)
658 default_options
= { :action => action
.to_s
}
659 require_id
= !resource
.kind_of
?(SingletonResource
)
661 case default_options
[:action]
662 when "index", "new"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :get)).merge(resource
.requirements
)
663 when "create"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :post)).merge(resource
.requirements
)
664 when "show", "edit"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :get)).merge(resource
.requirements(require_id
))
665 when "update"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :put)).merge(resource
.requirements(require_id
))
666 when "destroy"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :delete)).merge(resource
.requirements(require_id
))
667 else default_options
.merge(add_conditions_for(resource
.conditions
, method
)).merge(resource
.requirements
)
673 class ActionController
::Routing::RouteSet::Mapper
674 include ActionController
::Resources