Skip to content
Browse files

Allow a defining custom member field on resources

By default, resources routes are created with :resource/:id. A model
defining to_param can make prettier urls by using something more
readable than an integer ID, but since the route picks it up as :id you
wind up with awkward User.find_by_username(params[:id]) calls.

By overriding the key to be used in @request.params you can be more
obvious in your intent.
  • Loading branch information...
1 parent 8954ee6 commit 3e67e45dc327631e085cc67aaa6522b44324364c @jamie jamie committed Mar 25, 2012
Showing with 23 additions and 4 deletions.
  1. +5 −4 actionpack/lib/action_dispatch/routing/mapper.rb
  2. +18 −0 actionpack/test/dispatch/routing_test.rb
View
9 actionpack/lib/action_dispatch/routing/mapper.rb
@@ -880,17 +880,18 @@ module Resources
# CANONICAL_ACTIONS holds all actions that does not need a prefix or
# a path appended since they fit properly in their scope level.
VALID_ON_OPTIONS = [:new, :collection, :member]
- RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except]
+ RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param]
CANONICAL_ACTIONS = %w(index create new show update destroy)
class Resource #:nodoc:
- attr_reader :controller, :path, :options
+ attr_reader :controller, :path, :options, :param
def initialize(entities, options = {})
@name = entities.to_s
@path = (options[:path] || @name).to_s
@controller = (options[:controller] || @name).to_s
@as = options[:as]
+ @param = options[:param] || :id
@options = options
end
@@ -935,15 +936,15 @@ def resource_scope
alias :collection_scope :path
def member_scope
- "#{path}/:id"
+ "#{path}/:#{param}"
end
def new_scope(new_path)
"#{path}/#{new_path}"
end
def nested_scope
- "#{path}/:#{singular}_id"
+ "#{path}/:#{singular}_#{param}"
end
end
View
18 actionpack/test/dispatch/routing_test.rb
@@ -475,6 +475,11 @@ def self.call(params, request)
get :preview, :on => :member
end
+ resources :profiles, :param => :username do
+ get :details, :on => :member
+ resources :messages
+ end
+
scope :as => "routes" do
get "/c/:id", :as => :collision, :to => "collision#show"
get "/collision", :to => "collision#show"
@@ -2183,6 +2188,19 @@ def test_root_in_deeply_nested_scope
assert_equal "/posts/1/admin", post_admin_root_path(:post_id => '1')
end
+ def test_custom_param
+ get '/profiles/bob'
+ assert_equal 'profiles#show', @response.body
+ assert_equal 'bob', @request.params[:username]
+
+ get '/profiles/bob/details'
+ assert_equal 'bob', @request.params[:username]
+
+ get '/profiles/bob/messages/34'
+ assert_equal 'bob', @request.params[:profile_username]
+ assert_equal '34', @request.params[:id]
+ end
+
private
def with_https
old_https = https?

0 comments on commit 3e67e45

Please sign in to comment.
Something went wrong with that request. Please try again.