具有约束的复杂路线

时间:2017-10-18 14:55:49

标签: phoenix-framework

假设我有一个使用此资源的旅行社申请:

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

我想在索引模板中显示与请求网址匹配的所有航班。但我希望通过kayak.com路线提供:http://localhost:4000/flights/FRA-MIA/2017-12-01/2017-12-08

https://hexdocs.pm/phoenix/routing.html的官方文件中,我无法找到与此类似的例子。我需要FRAMIA2017-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}/ }

之类的东西

我如何在凤凰城解决这个问题?

1 个答案:

答案 0 :(得分: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