Turbocharge Your Ecto Schemas with This One Trick
Elixir’s naming conventions use question marks to indicate boolean values: “Functions that return a boolean are named with a trailing question mark.”
Why don’t Ecto schemas let us do the same?
In an ecto schema, field names map 1-to-1 with database column names. For instance, on John Elm Labs I have a field in my users table that tells me if someone is a lifetime subscriber or not:
schema "my_table" do
field :lifetime_subscriber, :boolean
end
I wanted to add a question mark to more readily indicate that it’s a boolean field. I tried to do:
field :lifetime_subscriber?
Which promptly threw a lovely ERROR 42703 (undefined_column) column ... does not exist
error in the console.
This is where the :source
option of field/3 comes to the rescue.
The documentation says the :source
option “defines the name that is to be used in the database for this field.”
Now, I can redefine my column like so:
field :lifetime_subscriber?, :boolean, source: :lifetime_subscriber
and it’s much more obvious to me in the rest of the code that this struct field represents a boolean value.
Column Renaming
The :source
option is more powerful than allowing one to follow naming conventions more closely. It can be used to “rename” columns without migrating the database - turning a potentially risky operation into a safe one. Read more about that in this safe ecto migrations post from Fly.io