Remapping Ecto fields to existing columns

Notes

We don’t always have the luxury to work with a brand new applications or databases.

When we have an existing database that we’re connecting to, but we don’t want to pollute our Ecto schemas with old database column names (maybe they’re bad or maybe we understand the domain better), Ecto has an awesome solution for us.

When we use field in schemas, we can define a new name for your field, and pass the original column name as source:.

So, instead of having to live with “checked” in our app:

field :body, :string
field :checked, :string

We can rename it to “completed”:

field :body, :string
field :completed, :string, source: :checked

We get to use the new name throughout our app, and at the last minute, Ecto transforms it to the column name for the query.

For more, check out field/3.

Want the latest Elixir Streams in your inbox?

    No spam. Unsubscribe any time.