前面的章節(jié)里,我們完成了后端系統(tǒng)最重要的部分:用戶。接下來(lái)我們要進(jìn)入菜譜模塊的開(kāi)發(fā)。
我們先來(lái)確認(rèn)下,菜譜有哪些屬性需要保存:
屬性名 | 類(lèi)型 | 備注 | 是否必填 | 默認(rèn)值 |
---|---|---|---|---|
name | string | 菜譜名 | 必填 | |
title | string | 節(jié)目名 | 必填 | |
season | integer | 第幾季 | 必填 | 1 |
episode | integer | 第幾集 | 必填 | 1 |
content | text | 內(nèi)容 | 必填 | |
user_id | integer | 關(guān)聯(lián)用戶 id | 必填 |
這里我們可以直接使用 mix phx.gen.html
命令來(lái)生成菜譜相關(guān)的所有文件:
$ mix phx.gen.html Recipes Recipe recipes name title season:integer episode:integer content:text user_id:references:users
* creating web/controllers/recipe_controller.ex
* creating web/templates/recipe/edit.html.eex
* creating web/templates/recipe/form.html.eex
* creating web/templates/recipe/index.html.eex
* creating web/templates/recipe/new.html.eex
* creating web/templates/recipe/show.html.eex
* creating web/views/recipe_view.ex
* creating test/controllers/recipe_controller_test.exs
* creating web/models/recipe.ex
* creating test/models/recipe_test.exs
* creating priv/repo/migrations/20170206013306_create_recipe.exs
Add the resource to your browser scope in web/router.ex:
resources "/recipes", RecipeController
Remember to update your repository by running migrations:
$ mix ecto.migrate

我們先按照提示把 resources "/recipes", RecipeController
加入 web/router.ex
文件中:
diff --git a/web/router.ex b/web/router.ex
index e0811dc..a6d7cd5 100644
--- a/web/router.ex
+++ b/web/router.ex
@@ -20,6 +20,7 @@ defmodule TvRecipeWeb.Router do
get "/", PageController, :index
resources "/users", UserController, except: [:index, :delete]
resources "/sessions", SessionController, only: [:new, :create, :delete]
+ resources "/recipes", RecipeController
end
但請(qǐng)不要著急執(zhí)行 mix ecto.migrate
,我們有幾個(gè)需要調(diào)整的地方:
注: 運(yùn)行了的話可使用 mix ecto.rollback
回撤修改
-
新建的
priv/repo/migrations/20170206013306_create_recipe.exs
文件中,有如下一句代碼:add :user_id, references(:users, on_delete: :nothing)
on_delete
決定recipe
關(guān)聯(lián)的user
被刪時(shí),我們要如何處置recipe
。:nothing
表示不動(dòng)recipe
,:delete_all
表示悉數(shù)刪除,這里我們使用:delete_all
。 -
新建的
lib/tv_recipe/recipes/recipe.ex
文件中,有一句代碼要替換:-field :user_id, :id +belongs_to :user, TvRecipe.Users.User
因?yàn)?
Recipe
與User
的關(guān)系是雙向的,所以我們需要在user.ex
文件中增加一句:has_many :recipes, TvRecipe.Recipes.Recipe
-
我們需要在
recipe.ex
文件中給season
與episode
設(shè)置默認(rèn)值:field :season, :integer, default: 1 field :episode, :integer, default: 1
現(xiàn)在,我們可以執(zhí)行 mix ecto.migrate
了:
$ mix ecto.migrate
12:45:54.141 [info] == Running TvRecipe.Repo.Migrations.CreateRecipe.change/0 forward
12:45:54.141 [info] create table recipes
12:45:54.146 [info] create index recipes_user_id_index
12:45:54.149 [info] == Migrated in 0.0s
我們運(yùn)行下測(cè)試看看:
$ mix test
mix test
Compiling 24 files (.ex)
Generated tv_recipe app
...............................................
Finished in 0.5 seconds
47 tests, 0 failures
新生成的測(cè)試目前悉數(shù)通過(guò)。
更多建議: