Riferimento rapido

Foglio di riferimento Phoenix Routing

Guida rapida di riferimento per Phoenix Router: verbi HTTP, route di risorse, helper di percorso, risorse nidificate e scope.

· Pubblicato

Phoenix Router offre un routing espressivo per associare richieste HTTP ad azioni di controller e LiveView tramite pipeline.

Ispezione delle route (Inspecting Routes)

# Stampare tutte le route definite
mix phx.routes

Routing delle risorse (Resource Routing)

# Genera tutte le 7 azioni RESTful standard
resources "/users", UserController

# Limitare le azioni generate
resources "/posts", PostController, only: [:index, :show]
resources "/comments", CommentController, except: [:delete]

Mappatura delle route RESTful generate

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)

Risorse nidificate (Nested Resources)

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

Genera helper nidificati:

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

Scope e pipeline (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

Riferimenti correlati

Argomenti correlati