【发布时间】:2016-09-13 00:53:40
【问题描述】:
假设我想创建一个 resources 并为其添加几个自定义操作,rails 中的类似物是:
resources :tasks do
member do
get :implement
end
end
这不仅会返回 7 条标准路线,还会返回 1 条新路线:
GET /tasks/:id/implement
在凤凰怎么做?
【问题讨论】:
假设我想创建一个 resources 并为其添加几个自定义操作,rails 中的类似物是:
resources :tasks do
member do
get :implement
end
end
这不仅会返回 7 条标准路线,还会返回 1 条新路线:
GET /tasks/:id/implement
在凤凰怎么做?
【问题讨论】:
您可以在resources 的do 块内添加get。
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之类的东西?
我想稍微改进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)调用它。不过,不是很干燥。
看起来收集路线必须是:
get "tasks/implement", Tasks, :implement # collection route
我认为 phoenix 没有像 rails 那样的成员/收集资源路由。
我找到了这个链接,他们谈论了一些收集路线,并举了一个像我上面提到的例子:
【讨论】:
这是另一个解决方案:
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 操作的路径。
【讨论】: