2017-10-18 109 views
0

假設我有一個旅行社報名與該資源:複雜的路線與約束

mix phx.gen.html Flights Flight flights departure destination 
           starts_on ends_on 
           flight_number price:integer 

我要顯示在索引模板匹配請求URL所有航班。但我想有一個像kayak.com路線可用:http://localhost:4000/flights/FRA-MIA/2017-12-01/2017-12-08

在官方文檔https://hexdocs.pm/phoenix/routing.html我找不到類似的例子。我需要FRA,MIA,2017-12-012017-12-08作爲參數。

生成的路線是這樣的:

resources "/flights", FlightController 

我想我可以用get_flight!/1功能拆分id但感覺很髒。有沒有更好的辦法?

在Ruby on Rails的我會使用類似match "/flights/:from-:destination/:year(/:month(/:day))..." => "flights#index", :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ }

我怎樣才能在鳳凰城解決這個問題?

回答

0

的lib/xyz_web/router.ex

get "/flights/:departure/:destination/:starts_on/:ends_on", PageController, :index 

會導致這樣的:

[info] GET /flights/FRA/MIA/2017-12-01/2017-12-08 
[debug] Processing with XyzWeb.PageController.index/2 
    Parameters: %{"departure" => "FRA", "destination" => "MIA", 
    "ends_on" => "2017-12-08", "starts_on" => "2017-12-01"} 
    Pipelines: [:browser] 

當然這是沒有約束。

控制器:

def index(conn, %{"starts_on" => starts_on, "ends_on" => ends_on, 
        "departure" => departure, 
        "destination" => destination }) do 
    what_ever = ... 
    render(conn, "index.html", what_ever: what_ever) 
end