rails routes optional parameters types by :id or :name
-
03-07-2021 - |
Question
Scenario:
I would like to have a url path where you could look someone up by an :id
or :name:
.
For user/5
or /user/tom
would all point to the same user
routes.rb
controller 'user' do
get 'user/:id'
get 'user/:name'
end
test/routes/user_routes.rb
test "/user/:id" do
assert_routing "/user/5", :controller => "user", :action => "find_by_id", :id=>"5"
end
test "/user/:name" do
assert_routing "/user/tom", :controller => "user", :action => "find_by_name", :name=>"tom"
end
I am not exactly sure if this is the right design decision with URL paths.
Looking for guidance
Solution
I don't think what you are doing is going to work, because the routes you gave are ambiguous, because rails routes can't say that url like user/15 has name or id.
Of course there is a way to do this, by specifying regular expression. Since id will always be a number, we can have regular expression check for it
controller 'user' do
get 'user/:id', :id => /\d+/
get 'user/:name', :name => /[A-Za-z][\w\s]+/
end
The above statements put a constraint of regular expression. In your controller you can check like
if params[:id]
# Get by id
else
# Get by name
You can also do this by passsing get parameters and handling it in controller in the same way.
Thanks