Elixir
Phoenix

RailsのscaffoldをPhoenixでやる

More than 3 years have passed since last update.

Railsのscaffoldと同じことがPhoenixでもできるっぽい。

とりあえずmix phoenix.gen.htmlでいけるっぽい


zsh

$ mix phoenix.gen.html User users name:string email:string bio:string number_of_pets:integer

Compiled lib/hello_phoenix.ex
Compiled web/web.ex
Compiled lib/hello_phoenix/repo.ex
Compiled web/router.ex
Compiled web/views/error_view.ex
Compiled web/controllers/page_controller.ex
Compiled web/views/page_view.ex
Compiled lib/hello_phoenix/endpoint.ex
Compiled web/views/layout_view.ex
Generated hello_phoenix app
* creating priv/repo/migrations/20150603150928_create_user.exs
* creating web/models/user.ex
* creating test/models/user_test.exs
* creating web/controllers/user_controller.ex
* creating web/templates/user/edit.html.eex
* creating web/templates/user/form.html.eex
* creating web/templates/user/index.html.eex
* creating web/templates/user/new.html.eex
* creating web/templates/user/show.html.eex
* creating web/views/user_view.ex
* creating test/controllers/user_controller_test.exs

Add the resource to the proper scope in web/router.ex:

resources "/users", UserController

and then update your repository by running migrations:

$ mix ecto.migrate


指示されているとおりにする。

まずは config/router.ex に追加する。


config/router.ex

defmodule HelloPhoenix.Router do

use HelloPhoenix.Web, :router

pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
end

pipeline :api do
plug :accepts, ["json"]
end

scope "/", HelloPhoenix do
pipe_through :browser # Use the default browser stack

get "/", PageController, :index
# ここらに突っ込む
resources "/users", UserController
end

# Other scopes may use custom stacks.
# scope "/api", HelloPhoenix do
# pipe_through :api
# end
end


userテーブル作るためにmigrateする。


zsh

$ mix ecto.migrate                                                                                                                 

[info] == Running HelloPhoenix.Repo.Migrations.CreateUser.change/0 forward
[info] create table users
[info] == Migrated in 0.1s


結果

http://localhost:4000/users

phoenix_scafolled.png


参考

http://www.phoenixframework.org/v0.13.1/docs/ecto-models