-
Notifications
You must be signed in to change notification settings - Fork 40
Custom generators
When creating new contexts, schemas or html files, we recommend using the Phoenix generators, phx.gen.context, phx.gen.schema and phx.gen.html.
We are using custom templates with these generators, and this wiki page is a guide to using the generators with these templates.
The custom templates add typespecs to the context and schema modules, and they also make several changes to the test cases.
After running the generator, you will need to make some small edits to the generated files.
The main change is to update the schema module type, replacing any with the correct type.
This example uses the following shell command, which you need to run in the root directory of the project,
to generate a Publications context module, a posts table and post* html files.
mix phx.gen.html Publications Post posts body title page_info_cache visibility_level published_at:utc_datetime user_id:references:usersAfter running the above command, you will need to edit the generated files (this example involves more editing because we have added the user association).
In the Vutuv.Publications module (lib/vutuv/socials.ex), change:
alias Vutuv.Repo
@type changeset_error :: {:error, Ecto.Changeset.t()}
alias Vutuv.Socials.Postto:
alias Vutuv.{Publications.Post, Repo}
@type changeset_error :: {:error, Ecto.Changeset.t()}In the Vutuv.Publications.Post module (lib/vutuv/publications/post.ex), change:
@type t :: %__MODULE__{
id: integer,
body: any,
page_info_cache: any,
published_at: any,
title: any,
visibility_level: any,
inserted_at: DateTime.t(),
updated_at: DateTime.t()
}to (changing any to the correct type and adding the user_id and user lines):
@type t :: %__MODULE__{
id: integer,
body: String.t(),
page_info_cache: String.t(),
published_at: DateTime.t(),
title: String.t(),
visibility_level: String.t(),
user_id: integer,
user: User.t() | %Ecto.Association.NotLoaded{},
inserted_at: DateTime.t(),
updated_at: DateTime.t()
}Also, replace field :user_id, :id with belongs_to :user, User in the schema function.
Then run mix format and mix test.
In this case, because we have added the user association, we need to make further edits to the
lib/vutuv/publications.ex and test/vutuv/socials/publications_test.exs files. These changes
involve adding a user argument to the list_posts, get_post! and create_post functions -
see the files mentioned above for details.