Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Ecto schema field name different than source table column name (Elixir)

I'm currently working on a Phoenix project where I'm unsatisfied with the way I'm calling fields in the templates.

The schema is currently

defmodule MyApp.Car do
  use MyApp.Web, :model
  schema "car" do
    field :columnName, :string
  end
end

car = Repo.get!(Car, id)

I'd like to be able to call the result with car.column_name rather than car.columnName

Migrating the database isn't currently an option due to a number of applications using the database.

like image 323
Tomos Rees Avatar asked Apr 13 '16 22:04

Tomos Rees


2 Answers

There is a source option for field.

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

defmodule MyApp.Car do
  use MyApp.Web, :model
  schema "car" do
    field :column_name, :string, source: :columnName
  end
end
like image 189
zwippie Avatar answered Oct 22 '22 09:10

zwippie


I believe this could be done Ecto's field source mapper.

defmodule MyApp.Car do
  use Ecto.Schema

  @field_source_mapper fn
    :column_name -> :columnName
    x -> x
  end

  schema "car" do
    field :column_name, :string
  end
end
like image 20
mralexlau Avatar answered Oct 22 '22 09:10

mralexlau