如何设置在查询字符串中采用多个参数的 Phoenix 路由

Eri*_*mer 2 routes phoenix-framework

我希望在凤凰城生成一条接受 2 个查询参数的路线。

get "/items?id=:id&action=:action", ActionController, :index_by

但我收到以下错误:

(Plug.Router.InvalidSpecError) :identifier in routes must be made of letters, numbers and underscores
Run Code Online (Sandbox Code Playgroud)

我注意到当我删除第二个参数时它编译得很好,所以我猜这与分隔符有关,&以分离查询字符串中的参数。

有没有另一种方法来指定多个参数来区分路线?

Bad*_*adu 5

路由定义主要用于“干净的 url”,因为它匹配请求路径(没有查询字符串)。

考虑到这一点,您可以像这样定义您的路线

get("item/:id/:action", ActionController, :index_by)
#Or
get("/items", ActionController, :index_by)
Run Code Online (Sandbox Code Playgroud)

第一个路由定义将捕获idaction从请求路径中获取,例如 GET /items/1/edit 将%{"id"=>1, "action"=>"edit"}在您的参数中提供。

第二个将捕获idaction来自查询字符串。例如GET "/items?id=1&action=delete"会给你%{"id"=>1, "action"=>"delete"}你的参数

请注意,与第一个路由定义不同,第二个路由定义不强制在查询字符串中出现idaction,因此您不能保证这些参数将在您的参数中可用。