jonbirke0927

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!

Most Liked

gregvaughn

gregvaughn

I vaguely remember that you can copy the Phoenix source file /priv/templates/phx.gen.schema/schema.ex to 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.

Matt

Matt

Hey Jonathan,

When you run a generator like phx.gen.context the 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. But use Ecto.Schema is not a dynamically generated. Check it out:

# /priv/templates/phg.gen.schema/schema.ex

defmodule <%= inspect schema.module %> do
  use Ecto.Schema
  import Ecto.Changeset
<%= if schema.prefix do %>
  @schema_prefix :<%= schema.prefix %><% end %><%= if schema.binary_id do %>
  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id<% end %>
  schema <%= inspect schema.table %> do
<%= for {k, v} <- schema.types do %>    field <%= inspect k %>, <%= Mix.Phoenix.Schema.type_and_opts_for_schema(v) %><%= schema.defaults[k] %><%= Mix.Phoenix.Schema.maybe_redact_field(k in schema.redacts) %>
<% end %><%= for {_, k, _, _} <- schema.assocs do %>    field <%= inspect k %>, <%= if schema.binary_id do %>:binary_id<% else %>:id<% end %>
<% end %>
    timestamps()
  end

  @doc false
  def changeset(<%= schema.singular %>, attrs) do
    <%= schema.singular %>
    |> cast(attrs, [<%= Enum.map_join(schema.attrs, ", ", &inspect(elem(&1, 0))) %>])
    |> validate_required([<%= Enum.map_join(schema.attrs, ", ", &inspect(elem(&1, 0))) %>])
<%= for k <- schema.uniques do %>    |> unique_constraint(<%= inspect k %>)
<% end %>  end
end

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:

  • Edit as you generate,
  • Automate the changes within your editor or a command line program like sed, or
  • Clone Phoenix and then edit the templates. You can then generate/move your project as you would if creating a project from an unreleased version. ← this seems messy to me.

If I was in your position, I would create an interactive Emacs command to take care of renaming Ecto.Schema to MyApp.Schema after generating a schema.

Where Next?

Popular in Questions Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement