How Ecto field_source_mapper works

The mapper is just for changing the columns names. It only receives the column name as an argument and is expected to return just a column name. From the docs:

In other words, it is a mechanism to automatically generate the :source
option for the field macro. It defaults to fn x -> x end, where no
field transformation is done;

And then the :source option docs from the field macro:

:source - Defines the name that is to be used in database for this field.

I guess I’m somewhat foolishly realizing that the way I used it in my previous example (mapping two of the fields directly) is better left for the :source option like so:

schema "users" do
  field :name, :string, [source: :username]
  field :location, :string, [source: users_current_location]
  field :foo, :string
end

The @field_source_mapper seems more appropriate for when you want to map all columns names following a similar pattern. In fact, it looks like @field_source_mapper will be ignored whenever :source is set on the fields, seen here:

  source = opts[:source] || Module.get_attribute(mod, :field_source_mapper).(name)
2 Likes