Module: ActionDispatch::Routing::Mapper::Resources
- Included in:
- ActionDispatch::Routing::Mapper
- Defined in:
- lib/action_dispatch/routing/mapper.rb
Overview
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:
resources :photos
Sometimes, you have a resource that clients always look up without referencing an ID. A common example, /profile always shows the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action.
resource :profile
It’s common to have resources that are logically children of other resources:
resources :magazines do
resources :ads
end
You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an admin
namespace. You would place these controllers under the app/controllers/admin
directory, and you can group them together in your router:
namespace "admin" do
resources :posts, :comments
end
By default the :id
parameter doesn’t accept dots. If you need to use dots as part of the :id
parameter add a constraint which overrides this restriction, e.g:
resources :articles, id: /[^\/]+/
This allows any character other than a slash as part of your :id
.
Defined Under Namespace
Classes: Resource, SingletonResource
Constant Summary collapse
- VALID_ON_OPTIONS =
CANONICAL_ACTIONS holds all actions that does not need a prefix or a path appended since they fit properly in their scope level.
[:new, :collection, :member]
- RESOURCE_OPTIONS =
[:as, :controller, :path, :only, :except, :param, :concerns]
- CANONICAL_ACTIONS =
%w(index create new show update destroy)
Instance Method Summary collapse
-
#add_route(action, controller, options, _path, to, via, formatted, anchor, options_constraints) ⇒ Object
:nodoc:.
-
#collection ⇒ Object
To add a route to the collection:.
-
#decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) ⇒ Object
:nodoc:.
- #get_to_from_path(path, to, action) ⇒ Object
-
#match(path, *rest) ⇒ Object
Matches a url pattern to one or more routes.
-
#member ⇒ Object
To add a member route, add a member block into the resource block:.
-
#namespace(path, options = {}) ⇒ Object
See ActionDispatch::Routing::Mapper::Scoping#namespace.
- #nested ⇒ Object
- #new ⇒ Object
-
#resource(*resources, &block) ⇒ Object
Sometimes, you have a resource that clients always look up without referencing an ID.
-
#resources(*resources, &block) ⇒ Object
In Rails, a resourceful route provides a mapping between HTTP verbs and URLs and controller actions.
- #resources_path_names(options) ⇒ Object
-
#root(path, options = {}) ⇒ Object
You can specify what Rails should route “/” to with the root method:.
- #shallow ⇒ Object
- #shallow? ⇒ Boolean
- #using_match_shorthand?(path) ⇒ Boolean
Instance Method Details
#add_route(action, controller, options, _path, to, via, formatted, anchor, options_constraints) ⇒ Object
:nodoc:
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1675 def add_route(action, controller, , _path, to, via, formatted, anchor, ) # :nodoc: path = path_for_action(action, _path) raise ArgumentError, "path is required" if path.blank? action = action.to_s default_action = .delete(:action) || @scope[:action] if action =~ /^[\w\-\/]+$/ default_action ||= action.tr('-', '_') unless action.include?("/") else action = nil end as = if !.fetch(:as, true) # if it's set to nil or false .delete(:as) else name_for_action(.delete(:as), action) end path = Mapping.normalize_path URI.parser.escape(path), formatted ast = Journey::Parser.parse path mapping = Mapping.build(@scope, @set, ast, controller, default_action, to, via, formatted, , anchor, ) @set.add_route(mapping, ast, as, anchor) end |
#collection ⇒ Object
To add a route to the collection:
resources :photos do
collection do
get 'search'
end
end
This will enable Rails to recognize paths such as /photos/search
with GET, and route to the search action of PhotosController
. It will also create the search_photos_url
and search_photos_path
route helpers.
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1472 def collection unless resource_scope? raise ArgumentError, "can't use collection outside resource(s) scope" end with_scope_level(:collection) do path_scope(parent_resource.collection_scope) do yield end end end |
#decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) ⇒ Object
:nodoc:
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1660 def decomposed_match(path, controller, , _path, to, via, formatted, anchor, ) # :nodoc: if on = .delete(:on) send(on) { decomposed_match(path, controller, , _path, to, via, formatted, anchor, ) } else case @scope.scope_level when :resources nested { decomposed_match(path, controller, , _path, to, via, formatted, anchor, ) } when :resource member { decomposed_match(path, controller, , _path, to, via, formatted, anchor, ) } else add_route(path, controller, , _path, to, via, formatted, anchor, ) end end end |
#get_to_from_path(path, to, action) ⇒ Object
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1645 def get_to_from_path(path, to, action) return to if to || action path_without_format = path.sub(/\(\.:format\)$/, '') if using_match_shorthand?(path_without_format) path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1').tr("-", "_") else nil end end |
#match(path, *rest) ⇒ Object
Matches a url pattern to one or more routes. For more information, see match.
match 'path' => 'controller#action', via: patch
match 'path', to: 'controller#action', via: :post
match 'path', 'otherpath', on: :member, via: :get
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1569 def match(path, *rest) if rest.empty? && Hash === path = path path, to = .find { |name, _value| name.is_a?(String) } case to when Symbol [:action] = to when String if to =~ /#/ [:to] = to else [:controller] = to end else [:to] = to end .delete(path) paths = [path] else = rest.pop || {} paths = [path] + rest end if [:on] && !VALID_ON_OPTIONS.include?([:on]) raise ArgumentError, "Unknown scope #{on.inspect} given to :on" end if @scope[:to] [:to] ||= @scope[:to] end if @scope[:controller] && @scope[:action] [:to] ||= "#{@scope[:controller]}##{@scope[:action]}" end controller = .delete(:controller) || @scope[:controller] option_path = .delete :path to = .delete :to via = Mapping.check_via Array(.delete(:via) { @scope[:via] }) formatted = .delete(:format) { @scope[:format] } anchor = .delete(:anchor) { true } = .delete(:constraints) || {} path_types = paths.group_by(&:class) path_types.fetch(String, []).each do |_path| = .dup if _path && option_path ActiveSupport::Deprecation.warn <<-eowarn Specifying strings for both :path and the route path is deprecated. Change things like this: match #{_path.inspect}, :path => #{option_path.inspect} to this: match #{option_path.inspect}, :as => #{_path.inspect}, :action => #{path.inspect} eowarn [:action] = _path [:as] = _path _path = option_path end to = get_to_from_path(_path, to, [:action]) decomposed_match(_path, controller, , _path, to, via, formatted, anchor, ) end path_types.fetch(Symbol, []).each do |action| = .dup decomposed_match(action, controller, , option_path, to, via, formatted, anchor, ) end self end |
#member ⇒ Object
To add a member route, add a member block into the resource block:
resources :photos do
member do
get 'preview'
end
end
This will recognize /photos/1/preview
with GET, and route to the preview action of PhotosController
. It will also create the preview_photo_url
and preview_photo_path
helpers.
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1495 def member unless resource_scope? raise ArgumentError, "can't use member outside resource(s) scope" end with_scope_level(:member) do if shallow? shallow_scope { path_scope(parent_resource.member_scope) { yield } } else path_scope(parent_resource.member_scope) { yield } end end end |
#namespace(path, options = {}) ⇒ Object
See ActionDispatch::Routing::Mapper::Scoping#namespace
1544 1545 1546 1547 1548 1549 1550 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1544 def namespace(path, = {}) if resource_scope? nested { super } else super end end |
#nested ⇒ Object
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1523 def nested unless resource_scope? raise ArgumentError, "can't use nested outside resource(s) scope" end with_scope_level(:nested) do if shallow? && shallow_nesting_depth >= 1 shallow_scope do path_scope(parent_resource.nested_scope) do scope() { yield } end end else path_scope(parent_resource.nested_scope) do scope() { yield } end end end end |
#new ⇒ Object
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1511 def new unless resource_scope? raise ArgumentError, "can't use new outside resource(s) scope" end with_scope_level(:new) do path_scope(parent_resource.new_scope(action_path(:new))) do yield end end end |
#resource(*resources, &block) ⇒ Object
Sometimes, you have a resource that clients always look up without referencing an ID. A common example, /profile always shows the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action:
resource :profile
creates six different routes in your application, all mapping to the Profiles
controller (note that the controller is named after the plural):
GET /profile/new
POST /profile
GET /profile
GET /profile/edit
PATCH/PUT /profile
DELETE /profile
Options
Takes same options as resources
.
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1269 def resource(*resources, &block) = resources..dup if apply_common_behavior_for(:resource, resources, , &block) return self end with_scope_level(:resource) do = resource_scope(SingletonResource.new(resources.pop, api_only?, @scope[:shallow], )) do yield if block_given? concerns([:concerns]) if [:concerns] collection do post :create end if parent_resource.actions.include?(:create) new do get :new end if parent_resource.actions.include?(:new) set_member_mappings_for_resource end end self end |
#resources(*resources, &block) ⇒ Object
In Rails, a resourceful route provides a mapping between HTTP verbs and URLs and controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as
resources :photos
creates seven different routes in your application, all mapping to the Photos
controller:
GET /photos
GET /photos/new
POST /photos
GET /photos/:id
GET /photos/:id/edit
PATCH/PUT /photos/:id
DELETE /photos/:id
Resources can also be nested infinitely by using this block syntax:
resources :photos do
resources :comments
end
This generates the following comments routes:
GET /photos/:photo_id/comments
GET /photos/:photo_id/comments/new
POST /photos/:photo_id/comments
GET /photos/:photo_id/comments/:id
GET /photos/:photo_id/comments/:id/edit
PATCH/PUT /photos/:photo_id/comments/:id
DELETE /photos/:photo_id/comments/:id
Options
Takes same options as Base#match
as well as:
- :path_names
-
Allows you to change the segment component of the
edit
andnew
actions. Actions not specified are not changed.resources :posts, path_names: { new: "brand_new" }
The above example will now change /posts/new to /posts/brand_new
- :path
-
Allows you to change the path prefix for the resource.
resources :posts, path: 'postings'
The resource and all segments will now route to /postings instead of /posts
- :only
-
Only generate routes for the given actions.
resources :cows, only: :show resources :cows, only: [:show, :index]
- :except
-
Generate all routes except for the given actions.
resources :cows, except: :show resources :cows, except: [:show, :index]
- :shallow
-
Generates shallow routes for nested resource(s). When placed on a parent resource, generates shallow routes for all nested resources.
resources :posts, shallow: true do resources :comments end
Is the same as:
resources :posts do resources :comments, except: [:show, :edit, :update, :destroy] end resources :comments, only: [:show, :edit, :update, :destroy]
This allows URLs for resources that otherwise would be deeply nested such as a comment on a blog post like
/posts/a-long-permalink/comments/1234
to be shortened to just/comments/1234
. - :shallow_path
-
Prefixes nested shallow routes with the specified path.
scope shallow_path: "sekret" do resources :posts do resources :comments, shallow: true end end
The
comments
resource here will have the following routes generated for it:post_comments GET /posts/:post_id/comments(.:format) post_comments POST /posts/:post_id/comments(.:format) new_post_comment GET /posts/:post_id/comments/new(.:format) edit_comment GET /sekret/comments/:id/edit(.:format) comment GET /sekret/comments/:id(.:format) comment PATCH/PUT /sekret/comments/:id(.:format) comment DELETE /sekret/comments/:id(.:format)
- :shallow_prefix
-
Prefixes nested shallow route names with specified prefix.
scope shallow_prefix: "sekret" do resources :posts do resources :comments, shallow: true end end
The
comments
resource here will have the following routes generated for it:post_comments GET /posts/:post_id/comments(.:format) post_comments POST /posts/:post_id/comments(.:format) new_post_comment GET /posts/:post_id/comments/new(.:format) edit_sekret_comment GET /comments/:id/edit(.:format) sekret_comment GET /comments/:id(.:format) sekret_comment PATCH/PUT /comments/:id(.:format) sekret_comment DELETE /comments/:id(.:format)
- :format
-
Allows you to specify the default value for optional
format
segment or disable it by supplyingfalse
.
Examples
# routes call <tt>Admin::PostsController</tt>
resources :posts, module: "admin"
# resource actions are at /admin/posts.
resources :posts, path: "admin/posts"
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1430 def resources(*resources, &block) = resources..dup if apply_common_behavior_for(:resources, resources, , &block) return self end with_scope_level(:resources) do = resource_scope(Resource.new(resources.pop, api_only?, @scope[:shallow], )) do yield if block_given? concerns([:concerns]) if [:concerns] collection do get :index if parent_resource.actions.include?(:index) post :create if parent_resource.actions.include?(:create) end new do get :new end if parent_resource.actions.include?(:new) set_member_mappings_for_resource end end self end |
#resources_path_names(options) ⇒ Object
1244 1245 1246 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1244 def resources_path_names() @scope[:path_names].merge!() end |
#root(path, options = {}) ⇒ Object
You can specify what Rails should route “/” to with the root method:
root to: 'pages#main'
For options, see match
, as root
uses it internally.
You can also pass a string which will expand
root 'pages#main'
You should put the root route at the top of config/routes.rb
, because this means it will be matched first. As this is the most popular route of most Rails applications, this is beneficial.
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1715 def root(path, = {}) if path.is_a?(String) [:to] = path elsif path.is_a?(Hash) and .empty? = path else raise ArgumentError, "must be called with a path and/or options" end if @scope.resources? with_scope_level(:root) do path_scope(parent_resource.path) do match_root_route() end end else match_root_route() end end |
#shallow ⇒ Object
1552 1553 1554 1555 1556 1557 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1552 def shallow @scope = @scope.new(shallow: true) yield ensure @scope = @scope.parent end |
#shallow? ⇒ Boolean
1559 1560 1561 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1559 def shallow? !parent_resource.singleton? && @scope[:shallow] end |
#using_match_shorthand?(path) ⇒ Boolean
1656 1657 1658 |
# File 'lib/action_dispatch/routing/mapper.rb', line 1656 def using_match_shorthand?(path) path =~ %r{^/?[-\w]+/[-\w/]+$} end |