【问题标题】:Is there any way to define custom routes in Phoenix?有没有办法在 Phoenix 中定义自定义路线?
【发布时间】:2016-09-13 00:53:40
【问题描述】:

假设我想创建一个 resources 并为其添加几个自定义操作,rails 中的类似物是:

resources :tasks do
  member do
    get :implement
  end
end

这不仅会返回 7 条标准路线,还会返回 1 条新路线:

GET /tasks/:id/implement

在凤凰怎么做?

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

    您可以在resourcesdo 块内添加get

    web/router.ex

    resources "/tasks", TaskController do
      get "/implement", TaskController, :implement
    end
    

    $ mix phoenix.routes

         task_path  GET     /tasks                     MyApp.TaskController :index
         task_path  GET     /tasks/:id/edit            MyApp.TaskController :edit
         task_path  GET     /tasks/new                 MyApp.TaskController :new
         task_path  GET     /tasks/:id                 MyApp.TaskController :show
         task_path  POST    /tasks                     MyApp.TaskController :create
         task_path  PATCH   /tasks/:id                 MyApp.TaskController :update
                    PUT     /tasks/:id                 MyApp.TaskController :update
         task_path  DELETE  /tasks/:id                 MyApp.TaskController :delete
    task_task_path  GET     /tasks/:task_id/implement  MyApp.TaskController :implement
    

    【讨论】:

    • 如何在这个元素中描述collection
    • 也想知道如何将它与资源下的收集路由一起使用。
    • get "tasks/implement", Tasks, :implement # 收集路线
    • 如何定义GET /tasks/implement之类的东西?
    【解决方案2】:

    我想稍微改进Dogbert的回答:

    resources "/tasks", TaskController do
      get "/implement", TaskController, :implement, as: :implement
    end
    

    唯一添加的是路径末尾的as: :implement

    因此,您将获得名为 task_implement_path 的路由,而不是丑陋的 task_task_path

    【讨论】:

    • 这确实是一个非常好的提示。
    • 你如何描述收集路线?
    • 我收到了undefined function task_implement_path/1,你知道吗?
    • 好吧,我用task_implement_path(task)而不是task_implement_path(conn, :implement, task)调用它。不过,不是很干燥。
    【解决方案3】:

    看起来收集路线必须是:

    get "tasks/implement", Tasks, :implement # collection route
    

    我认为 phoenix 没有像 rails 那样的成员/收集资源路由。

    我找到了这个链接,他们谈论了一些收集路线,并举了一个像我上面提到的例子:

    https://github.com/phoenixframework/phoenix/issues/10

    【讨论】:

      【解决方案4】:

      这是另一个解决方案:

      scope "/tasks" do
        get "/:id/implement", TasksController, :implement
        get "/done", TasksController, :done
      end
      resources "/tasks", TasksController
      

      implement 动作有一个 member 路由,done 动作有一个 collection 路由。

      你可以通过这个函数调用获得前者的路径:

      tasks_path(@conn, :implement, task)
      

      请注意,您应该将resources置于 scope 块之后。否则,Phoenix 会将/tasks/done 识别为show 操作的路径。

      【讨论】:

        猜你喜欢
        • 2019-11-28
        • 1970-01-01
        • 2021-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        • 2022-09-27
        • 2020-12-27
        相关资源
        最近更新 更多