Szybka pomoc

Ściągawka z routingu w Phoenixie

Szybki przewodnik po Phoenix Router: metody HTTP, trasy zasobów resources, funkcje pomocnicze helpery, zagnieżdżone zasoby i zakresy scopes.

· Opublikowano

Phoenix Router zapewnia ekspresyjny mechanizm routingu łączący żądania HTTP z akcjami kontrolera i LiveViews za pomocą potoków.

Inspekcja tras (Inspecting Routes)

# Wyswietlenie zdefiniowanych tras i helperow
mix phx.routes

Routing zasobów (Resource Routing)

# Generuje wszystkie 7 akcji RESTful
resources "/users", UserController

# Ograniczenie generowanych akcji
resources "/posts", PostController, only: [:index, :show]
resources "/comments", CommentController, except: [:delete]

Mapowanie wygenerowanych tras RESTful

HTTP Verb Path Action Helper Function
GET /users :index Routes.user_path(conn, :index)
GET /users/new :new Routes.user_path(conn, :new)
POST /users :create Routes.user_path(conn, :create)
GET /users/:id :show Routes.user_path(conn, :show, id)
GET /users/:id/edit :edit Routes.user_path(conn, :edit, id)
PUT / PATCH /users/:id :update Routes.user_path(conn, :update, id)
DELETE /users/:id :delete Routes.user_path(conn, :delete, id)

Zagnieżdżone zasoby (Nested Resources)

resources "/users", UserController do
  resources "/posts", PostController
end

Generuje zagniezdzone helpery:

# Routes.user_post_path(conn, :index, user_id)
# Routes.user_post_path(conn, :show, user_id, post_id)

Zakresy i potoki (Scopes & Pipelines)

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :protect_from_forgery
end

pipeline :api do
  plug :accepts, ["json"]
end

scope "/api", MyAppWeb.Api, as: :api do
  pipe_through :api

  resources "/articles", ArticleController
end

Powiązane materiały

Powiązane tematy