Change Default Behaviors
Learn how to change the default conventions of Ecto.
We'll cover the following
Ecto’s migrations follow a number of conventions that have proven to work well over time. In most cases, it’s easiest to follow those conventions. They usually require less code and can reduce ramp-up time for new developers joining the project. It’s always helpful if a new project looks a lot like our last one. Sometimes, though, Ecto’s conventions won’t fit our project and we need to structure things differently. Fortunately, Ecto offers several escape hatches that allow us to craft our migrations as needed. This section will look at different ways we can customize migration behavior.
Setting primary key names
Earlier in this chapter, we saw how Ecto automatically creates a primary key called id
with type :bigserial
when creating a new table. Suppose we’d like Ecto to use a different name and type when creating primary keys. In that case, we can set this as a global configuration option in our Repo
config in config/config.exs
(we looked at some of these configurations settings here). Here’s how we could use code
instead of id
as the column name and :string
as the type.
Get hands-on with 1400+ tech skills courses.