2016-01-15 20 views
3

我想要做的是根據可用於數據庫中特定模型的slu dynamically動態路由頂級路徑,例如GitHub如何爲用戶/組織名稱https://github.com/elixir-langhttps://github.com/phoenixframework,但我似乎無法在PhoenixFramework中找到我的頭。動態定義菲尼克斯路線中的頂級路線.ex

我到目前爲止已經試過,在我routes.ex是:

Enum.each(MyApp.Repo.all(MyApp.User), fn section -> 
    get "/#{user.username}", UserController, :show, assigns: %{"username" => user.username} 
end) 

但我結束了以下錯誤,當它試圖編譯應用程序:

== Compilation error on file web/router.ex == 
** (ArgumentError) repo MyApp.Repo is not started, please ensure it is part of your supervision tree 
    lib/ecto/query/planner.ex:91: Ecto.Query.Planner.cache_lookup/3 
    lib/ecto/query/planner.ex:72: Ecto.Query.Planner.query/4 
    lib/ecto/repo/queryable.ex:91: Ecto.Repo.Queryable.execute/5 
    lib/ecto/repo/queryable.ex:15: Ecto.Repo.Queryable.all/4 
    web/router.ex:25: (module) 
    (stdlib) erl_eval.erl:669: :erl_eval.do_apply/6 
    (elixir) lib/kernel/parallel_compiler.ex:100: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/8 

回答

3

routes.ex是DSL ,這是在編譯期間解析的,而不是在運行時。錯誤信息中的前兩個單詞是Compilation error。這意味着,你不能在你的路線中使用數據庫。

相反,嘗試定義這樣的頂級路線:

get /:user_slug, UserController, :show 

在你的控制器,檢查該用戶是否在數據庫中存在,並返回404,如果不是。

2

我寫了一篇博客文章如何做到這一點:

http://www.adamcz.com/blog/pretty-urls-with-phoenix

如果你已經在數據庫中蛞蝓,你只需要在你的路由器文件中指定帕拉姆:

resources "/users", UserController, only: [:index, ...], param: "slug"

,然後尋找一個PARAM在你的控制器:

def show(conn, %("slug" => slug}) do user = Repo.get_by(User, slug: slug)