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
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 ||= @options[:shallow] ? @options[:namespace].try(:sub, /\/$/, '') : path_prefix
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 ||= @options[:shallow] ? @options[:namespace].try(:gsub, /\//, '_') : name_prefix
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
) || action_allowed
?(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
, except
= @options.values_at(:only, :except)
139 @allowed_actions ||= {}
141 if only
== :all || except
== :none
144 elsif only
== :none || except
== :all
150 @allowed_actions[:only] = Array(only
).map(&:to_sym)
152 @allowed_actions[:except] = Array(except
).map(&:to_sym)
156 def action_allowed
?(action
)
157 only
, except
= @allowed_actions.values_at(:only, :except)
158 (!only
|| only
.include?(action
)) && (!except
|| !except
.include?(action
))
162 @path_prefix = options
.delete(:path_prefix)
163 @name_prefix = options
.delete(:name_prefix)
166 def arrange_actions_by_methods(actions
)
167 (actions
|| {}).inject({}) do |flipped_hash
, (key
, value
)|
168 (flipped_hash
[value
] ||= []) << key
173 def add_default_action(collection
, method
, action
)
174 (collection
[method
] ||= []).unshift(action
)
178 class SingletonResource
< Resource
#:nodoc:
179 def initialize(entity
, options
)
180 @singular = @plural = entity
181 options
[:controller] ||= @singular.to_s
.pluralize
185 alias_method
:shallow_path_prefix, :path_prefix
186 alias_method
:shallow_name_prefix, :name_prefix
187 alias_method
:member_path, :path
188 alias_method
:nesting_path_prefix, :path
191 # Creates named routes for implementing verb-oriented controllers
192 # for a collection \resource.
196 # map.resources :messages
198 # will map the following actions in the corresponding controller:
200 # class MessagesController < ActionController::Base
203 # # return all messages
206 # # GET new_message_url
208 # # return an HTML form for describing a new message
211 # # POST messages_url
213 # # create a new message
216 # # GET message_url(:id => 1)
218 # # find and return a specific message
221 # # GET edit_message_url(:id => 1)
223 # # return an HTML form for editing a specific message
226 # # PUT message_url(:id => 1)
228 # # find and update a specific message
231 # # DELETE message_url(:id => 1)
233 # # delete a specific message
237 # Along with the routes themselves, +resources+ generates named routes for use in
238 # controllers and views. <tt>map.resources :messages</tt> produces the following named routes and helpers:
240 # Named Route Helpers
241 # ============ =====================================================
242 # messages messages_url, hash_for_messages_url,
243 # messages_path, hash_for_messages_path
245 # message message_url(id), hash_for_message_url(id),
246 # message_path(id), hash_for_message_path(id)
248 # new_message new_message_url, hash_for_new_message_url,
249 # new_message_path, hash_for_new_message_path
251 # edit_message edit_message_url(id), hash_for_edit_message_url(id),
252 # edit_message_path(id), hash_for_edit_message_path(id)
254 # You can use these helpers instead of +url_for+ or methods that take +url_for+ parameters. For example:
256 # redirect_to :controller => 'messages', :action => 'index'
258 # <%= link_to "edit this message", :controller => 'messages', :action => 'edit', :id => @message.id %>
262 # redirect_to messages_url
264 # <%= link_to "edit this message", edit_message_url(@message) # calls @message.id automatically
266 # Since web browsers don't support the PUT and DELETE verbs, you will need to add a parameter '_method' to your
267 # form tags. The form helpers make this a little easier. For an update form with a <tt>@message</tt> object:
269 # <%= form_tag message_path(@message), :method => :put %>
273 # <% form_for :message, @message, :url => message_path(@message), :html => {:method => :put} do |f| %>
277 # <% form_for @message do |f| %>
279 # which takes into account whether <tt>@message</tt> is a new record or not and generates the
280 # path and method accordingly.
282 # The +resources+ method accepts the following options to customize the resulting routes:
283 # * <tt>:collection</tt> - Add named routes for other actions that operate on the collection.
284 # Takes a hash of <tt>#{action} => #{method}</tt>, where method is <tt>:get</tt>/<tt>:post</tt>/<tt>:put</tt>/<tt>:delete</tt>,
285 # an array of any of the previous, or <tt>:any</tt> if the method does not matter.
286 # These routes map to a URL like /messages/rss, with a route of +rss_messages_url+.
287 # * <tt>:member</tt> - Same as <tt>:collection</tt>, but for actions that operate on a specific member.
288 # * <tt>:new</tt> - Same as <tt>:collection</tt>, but for actions that operate on the new \resource action.
289 # * <tt>:controller</tt> - Specify the controller name for the routes.
290 # * <tt>:singular</tt> - Specify the singular name used in the member routes.
291 # * <tt>:requirements</tt> - Set custom routing parameter requirements; this is a hash of either
292 # regular expressions (which must match for the route to match) or extra parameters. For example:
294 # map.resource :profile, :path_prefix => ':name', :requirements => { :name => /[a-zA-Z]+/, :extra => 'value' }
296 # will only match if the first part is alphabetic, and will pass the parameter :extra to the controller.
297 # * <tt>:conditions</tt> - Specify custom routing recognition conditions. \Resources sets the <tt>:method</tt> value for the method-specific routes.
298 # * <tt>:as</tt> - Specify a different \resource name to use in the URL path. For example:
299 # # products_path == '/productos'
300 # map.resources :products, :as => 'productos' do |product|
301 # # product_reviews_path(product) == '/productos/1234/comentarios'
302 # product.resources :product_reviews, :as => 'comentarios'
305 # * <tt>:has_one</tt> - Specify nested \resources, this is a shorthand for mapping singleton \resources beneath the current.
306 # * <tt>:has_many</tt> - Same has <tt>:has_one</tt>, but for plural \resources.
308 # You may directly specify the routing association with +has_one+ and +has_many+ like:
310 # map.resources :notes, :has_one => :author, :has_many => [:comments, :attachments]
312 # This is the same as:
314 # map.resources :notes do |notes|
315 # notes.resource :author
316 # notes.resources :comments
317 # notes.resources :attachments
320 # * <tt>:path_names</tt> - Specify different names for the 'new' and 'edit' actions. For example:
321 # # new_products_path == '/productos/nuevo'
322 # map.resources :products, :as => 'productos', :path_names => { :new => 'nuevo', :edit => 'editar' }
324 # You can also set default action names from an environment, like this:
325 # config.action_controller.resources_path_names = { :new => 'nuevo', :edit => 'editar' }
327 # * <tt>:path_prefix</tt> - Set a prefix to the routes with required route variables.
329 # Weblog comments usually belong to a post, so you might use +resources+ like:
331 # map.resources :articles
332 # map.resources :comments, :path_prefix => '/articles/:article_id'
334 # You can nest +resources+ calls to set this automatically:
336 # map.resources :articles do |article|
337 # article.resources :comments
340 # The comment \resources work the same, but must now include a value for <tt>:article_id</tt>.
342 # article_comments_url(@article)
343 # article_comment_url(@article, @comment)
345 # article_comments_url(:article_id => @article)
346 # article_comment_url(:article_id => @article, :id => @comment)
348 # If you don't want to load all objects from the database you might want to use the <tt>article_id</tt> directly:
350 # articles_comments_url(@comment.article_id, @comment)
352 # * <tt>:name_prefix</tt> - Define a prefix for all generated routes, usually ending in an underscore.
353 # Use this if you have named routes that may clash.
355 # map.resources :tags, :path_prefix => '/books/:book_id', :name_prefix => 'book_'
356 # map.resources :tags, :path_prefix => '/toys/:toy_id', :name_prefix => 'toy_'
358 # You may also use <tt>:name_prefix</tt> to override the generic named routes in a nested \resource:
360 # map.resources :articles do |article|
361 # article.resources :comments, :name_prefix => nil
364 # This will yield named \resources like so:
366 # comments_url(@article)
367 # comment_url(@article, @comment)
369 # * <tt>:shallow</tt> - If true, paths for nested resources which reference a specific member
370 # (ie. those with an :id parameter) will not use the parent path prefix or name prefix.
372 # The <tt>:shallow</tt> option is inherited by any nested resource(s).
374 # For example, 'users', 'posts' and 'comments' all use shallow paths with the following nested resources:
376 # map.resources :users, :shallow => true do |user|
377 # user.resources :posts do |post|
378 # post.resources :comments
381 # # --> GET /users/1/posts (maps to the PostsController#index action as usual)
382 # # also adds the usual named route called "user_posts"
383 # # --> GET /posts/2 (maps to the PostsController#show action as if it were not nested)
384 # # also adds the named route called "post"
385 # # --> GET /posts/2/comments (maps to the CommentsController#index action)
386 # # also adds the named route called "post_comments"
387 # # --> GET /comments/2 (maps to the CommentsController#show action as if it were not nested)
388 # # also adds the named route called "comment"
390 # You may also use <tt>:shallow</tt> in combination with the +has_one+ and +has_many+ shorthand notations like:
392 # map.resources :users, :has_many => { :posts => :comments }, :shallow => true
394 # * <tt>:only</tt> and <tt>:except</tt> - Specify which of the seven default actions should be routed to.
396 # <tt>:only</tt> and <tt>:except</tt> may be set to <tt>:all</tt>, <tt>:none</tt>, an action name or a
397 # list of action names. By default, routes are generated for all seven actions.
401 # map.resources :posts, :only => [:index, :show] do |post|
402 # post.resources :comments, :except => [:update, :destroy]
404 # # --> GET /posts (maps to the PostsController#index action)
405 # # --> POST /posts (fails)
406 # # --> GET /posts/1 (maps to the PostsController#show action)
407 # # --> DELETE /posts/1 (fails)
408 # # --> POST /posts/1/comments (maps to the CommentsController#create action)
409 # # --> PUT /posts/1/comments/1 (fails)
411 # If <tt>map.resources</tt> is called with multiple resources, they all get the same options applied.
415 # map.resources :messages, :path_prefix => "/thread/:thread_id"
416 # # --> GET /thread/7/messages/1
418 # map.resources :messages, :collection => { :rss => :get }
419 # # --> GET /messages/rss (maps to the #rss action)
420 # # also adds a named route called "rss_messages"
422 # map.resources :messages, :member => { :mark => :post }
423 # # --> POST /messages/1/mark (maps to the #mark action)
424 # # also adds a named route called "mark_message"
426 # map.resources :messages, :new => { :preview => :post }
427 # # --> POST /messages/new/preview (maps to the #preview action)
428 # # also adds a named route called "preview_new_message"
430 # map.resources :messages, :new => { :new => :any, :preview => :post }
431 # # --> POST /messages/new/preview (maps to the #preview action)
432 # # also adds a named route called "preview_new_message"
433 # # --> /messages/new can be invoked via any request method
435 # map.resources :messages, :controller => "categories",
436 # :path_prefix => "/category/:category_id",
437 # :name_prefix => "category_"
438 # # --> GET /categories/7/messages/1
439 # # has named route "category_message"
441 # The +resources+ method sets HTTP method restrictions on the routes it generates. For example, making an
442 # HTTP POST on <tt>new_message_url</tt> will raise a RoutingError exception. The default route in
443 # <tt>config/routes.rb</tt> overrides this and allows invalid HTTP methods for \resource routes.
444 def resources(*entities
, &block
)
445 options
= entities
.extract_options
!
446 entities
.each
{ |entity
| map_resource(entity
, options
.dup
, &block
) }
449 # Creates named routes for implementing verb-oriented controllers for a singleton \resource.
450 # A singleton \resource is global to its current context. For unnested singleton \resources,
451 # the \resource is global to the current user visiting the application, such as a user's
452 # <tt>/account</tt> profile. For nested singleton \resources, the \resource is global to its parent
453 # \resource, such as a <tt>projects</tt> \resource that <tt>has_one :project_manager</tt>.
454 # The <tt>project_manager</tt> should be mapped as a singleton \resource under <tt>projects</tt>:
456 # map.resources :projects do |project|
457 # project.resource :project_manager
460 # See +resources+ for general conventions. These are the main differences:
461 # * A singular name is given to <tt>map.resource</tt>. The default controller name is still taken from the plural name.
462 # * To specify a custom plural name, use the <tt>:plural</tt> option. There is no <tt>:singular</tt> option.
463 # * No default index route is created for the singleton \resource controller.
464 # * When nesting singleton \resources, only the singular name is used as the path prefix (example: 'account/messages/1')
468 # map.resource :account
470 # maps these actions in the Accounts controller:
472 # class AccountsController < ActionController::Base
473 # # GET new_account_url
475 # # return an HTML form for describing the new account
480 # # create an account
485 # # find and return the account
488 # # GET edit_account_url
490 # # return an HTML form for editing the account
495 # # find and update the account
498 # # DELETE account_url
500 # # delete the account
504 # Along with the routes themselves, +resource+ generates named routes for
505 # use in controllers and views. <tt>map.resource :account</tt> produces
506 # these named routes and helpers:
508 # Named Route Helpers
509 # ============ =============================================
510 # account account_url, hash_for_account_url,
511 # account_path, hash_for_account_path
513 # new_account new_account_url, hash_for_new_account_url,
514 # new_account_path, hash_for_new_account_path
516 # edit_account edit_account_url, hash_for_edit_account_url,
517 # edit_account_path, hash_for_edit_account_path
518 def resource(*entities
, &block
)
519 options
= entities
.extract_options
!
520 entities
.each
{ |entity
| map_singleton_resource(entity
, options
.dup
, &block
) }
524 def map_resource(entities
, options
= {}, &block
)
525 resource
= Resource
.new(entities
, options
)
527 with_options
:controller => resource
.controller
do |map
|
528 map_collection_actions(map
, resource
)
529 map_default_collection_actions(map
, resource
)
530 map_new_actions(map
, resource
)
531 map_member_actions(map
, resource
)
533 map_associations(resource
, options
)
536 with_options(options
.slice(*INHERITABLE_OPTIONS
).merge(:path_prefix => resource
.nesting_path_prefix
, :name_prefix => resource
.nesting_name_prefix
), &block
)
541 def map_singleton_resource(entities
, options
= {}, &block
)
542 resource
= SingletonResource
.new(entities
, options
)
544 with_options
:controller => resource
.controller
do |map
|
545 map_collection_actions(map
, resource
)
546 map_new_actions(map
, resource
)
547 map_member_actions(map
, resource
)
548 map_default_singleton_actions(map
, resource
)
550 map_associations(resource
, options
)
553 with_options(options
.slice(*INHERITABLE_OPTIONS
).merge(:path_prefix => resource
.nesting_path_prefix
, :name_prefix => resource
.nesting_name_prefix
), &block
)
558 def map_associations(resource
, options
)
559 map_has_many_associations(resource
, options
.delete(:has_many), options
) if options
[:has_many]
561 path_prefix
= "#{options.delete(:path_prefix)}#{resource.nesting_path_prefix}"
562 name_prefix
= "#{options.delete(:name_prefix)}#{resource.nesting_name_prefix}"
564 Array(options
[:has_one]).each
do |association
|
565 resource(association
, options
.slice(*INHERITABLE_OPTIONS
).merge(:path_prefix => path_prefix
, :name_prefix => name_prefix
))
569 def map_has_many_associations(resource
, associations
, options
)
572 associations
.each
do |association
,has_many
|
573 map_has_many_associations(resource
, association
, options
.merge(:has_many => has_many
))
576 associations
.each
do |association
|
577 map_has_many_associations(resource
, association
, options
)
580 resources(associations
, options
.slice(*INHERITABLE_OPTIONS
).merge(:path_prefix => resource
.nesting_path_prefix
, :name_prefix => resource
.nesting_name_prefix
, :has_many => options
[:has_many]))
585 def map_collection_actions(map
, resource
)
586 resource
.collection_methods
.each
do |method
, actions
|
587 actions
.each
do |action
|
588 [method
].flatten
.each
do |m
|
589 map_resource_routes(map
, resource
, action
, "#{resource.path}#{resource.action_separator}#{action}", "#{action}_#{resource.name_prefix}#{resource.plural}", m
)
595 def map_default_collection_actions(map
, resource
)
596 index_route_name
= "#{resource.name_prefix}#{resource.plural}"
598 if resource
.uncountable
?
599 index_route_name
<< "_index"
602 map_resource_routes(map
, resource
, :index, resource
.path
, index_route_name
)
603 map_resource_routes(map
, resource
, :create, resource
.path
, index_route_name
)
606 def map_default_singleton_actions(map
, resource
)
607 map_resource_routes(map
, resource
, :create, resource
.path
, "#{resource.shallow_name_prefix}#{resource.singular}")
610 def map_new_actions(map
, resource
)
611 resource
.new_methods
.each
do |method
, actions
|
612 actions
.each
do |action
|
613 route_path
= resource
.new_path
614 route_name
= "new_#{resource.name_prefix}#{resource.singular}"
616 unless action
== :new
617 route_path
= "#{route_path}#{resource.action_separator}#{action}"
618 route_name
= "#{action}_#{route_name}"
621 map_resource_routes(map
, resource
, action
, route_path
, route_name
, method
)
626 def map_member_actions(map
, resource
)
627 resource
.member_methods
.each
do |method
, actions
|
628 actions
.each
do |action
|
629 [method
].flatten
.each
do |m
|
630 action_path
= resource
.options
[:path_names][action
] if resource
.options
[:path_names].is_a
?(Hash
)
631 action_path
||= Base
.resources_path_names
[action
] || action
633 map_resource_routes(map
, resource
, action
, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m
, { :force_id => true })
638 route_path
= "#{resource.shallow_name_prefix}#{resource.singular}"
639 map_resource_routes(map
, resource
, :show, resource
.member_path
, route_path
)
640 map_resource_routes(map
, resource
, :update, resource
.member_path
, route_path
)
641 map_resource_routes(map
, resource
, :destroy, resource
.member_path
, route_path
)
644 def map_resource_routes(map
, resource
, action
, route_path
, route_name
= nil, method
= nil, resource_options
= {} )
645 if resource
.has_action
?(action
)
646 action_options
= action_options_for(action
, resource
, method
, resource_options
)
647 formatted_route_path
= "#{route_path}.:format"
649 if route_name
&& @set.named_routes
[route_name
.to_sym
].nil?
650 map
.named_route(route_name
, formatted_route_path
, action_options
)
652 map
.connect(formatted_route_path
, action_options
)
657 def add_conditions_for(conditions
, method
)
658 returning({:conditions => conditions
.dup
}) do |options
|
659 options
[:conditions][:method] = method
unless method
== :any
663 def action_options_for(action
, resource
, method
= nil, resource_options
= {})
664 default_options
= { :action => action
.to_s
}
665 require_id
= !resource
.kind_of
?(SingletonResource
)
666 force_id
= resource_options
[:force_id] && !resource
.kind_of
?(SingletonResource
)
668 case default_options
[:action]
669 when "index", "new"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :get)).merge(resource
.requirements
)
670 when "create"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :post)).merge(resource
.requirements
)
671 when "show", "edit"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :get)).merge(resource
.requirements(require_id
))
672 when "update"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :put)).merge(resource
.requirements(require_id
))
673 when "destroy"; default_options
.merge(add_conditions_for(resource
.conditions
, method
|| :delete)).merge(resource
.requirements(require_id
))
674 else default_options
.merge(add_conditions_for(resource
.conditions
, method
)).merge(resource
.requirements(force_id
))