jonbirke0927
Configuring Phoenix generator to use a default schema when creating ecto schema
Hello everyone,
When using the phoenix generators to create a new context (i.e. mix phx.gen.context ContextName SchemaName table_name column_name:column_type), I continually run into an issue where the default schema being used in the new module is Ecto.Schema. The below code is an example of the code that would be generated using the command above:
defmodule MyApp.ContextName.SchemaName do
use Ecto.Schema
import Ecto.Changeset
...
end
My question is: is there a way to set the default schema to MyApp.Schema, instead of Ecto.Schema? If any app specific schema configurations have been implemented (such as primary_keys defaulting to uuid instead of integer_id), the generated schema will throw errors when you try to use it. It winds up being one of those problems that you don’t fix until you remember that you forgot to change use Ecto.Schema to use MyApp.Schema.
Thanks in advance!
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #hex
- #performance










First 2 of 2 Posts
Matt
Hey Jonathan,
When you run a generator like
phx.gen.contextthe content is obtained from a template. You can find the template in Phoenix’s source at/priv/templates/phx.gen.schema/schema.ex. When the generator is run, there is dynamic content generated such as the module name, fields, etc. Butuse Ecto.Schemais not a dynamically generated. Check it out:You can check out the above source here.
So, to answer your question:
There is no configuration variable or command line argument that will achieve what you’re looking for. Some of your options may be:
sed, orIf I was in your position, I would create an interactive Emacs command to take care of renaming
Ecto.SchematoMyApp.Schemaafter generating a schema.gregvaughn
I vaguely remember that you can copy the Phoenix source file
/priv/templates/phx.gen.schema/schema.exto your own project and edit the file and this version will be used by the generators.I couldn’t find docs, but I dug a bit deeper into the source and found that the helper module for the Phoenix generator tasks includes this function phoenix/lib/mix/phoenix.ex at v1.5.11 · phoenixframework/phoenix · GitHub
Which suggests you can copy the
schema.ex, make your edit and future generators will use it. It’s worth a try.