Snabbreferens

Phoenix Routing Lathund

Snabbreferens foer Phoenix Router: HTTP-metoder, resursrutter, sokvags-helpers, nastlade resurser och scopes.

· Publicerad

Phoenix Router erbjuder uttrycksfull routing foer att matcha HTTP-forfragnings till kontrolleratgarder och LiveViews via pipelines.

Inspektera rutter (Inspecting Routes)

# Skriv ut alla definierade rutter
mix phx.routes

Resursroutning (Resource Routing)

# Genererar alla 7 standard RESTful-atgarder
resources "/users", UserController

# Begransa genererade atgarder
resources "/posts", PostController, only: [:index, :show]
resources "/comments", CommentController, except: [:delete]

Genererad RESTful ruttmappning

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)

Nästlade resurser (Nested Resources)

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

Genererar nastlade helpers:

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

Omfång och pipelines (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

Relaterade referenser

Relaterade ämnen