场景:
我想要一个 url 路径,您可以在其中通过 :id
或 :name:
查找某人。
对于 user/5
或 /user/tom
都指向同一个用户
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
我不确定这是否是正确的 URL 路径设计决定。
寻求指导
最佳答案
我认为您正在做的事情不会奏效,因为您提供的路线不明确,因为 rails 路线不能说像 user/15 这样的 url 有名称或 ID。
当然有办法做到这一点,通过指定正则表达式。由于 id 始终是一个数字,我们可以对其进行正则表达式检查
controller 'user' do
get 'user/:id', :id => /\d+/
get 'user/:name', :name => /[A-Za-z][\w\s]+/
end
以上语句对正则表达式进行了约束。在您的 Controller 中,您可以检查一下
if params[:id]
# Get by id
else
# Get by name
您也可以通过传递 get 参数并以相同的方式在 Controller 中处理它来完成此操作。
谢谢
关于ruby-on-rails-3 - rails 通过 :id or :name 路由可选参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12518862/