8
votes

Let say I have a model, like that:

defmodule User do
  use MyApp.Web, :model

  schema "users" do
    field :email, :string
    field :first_name, :string

    belongs_to :role, Role
    has_many :comments, Comment
  end
end

User struct will be represented by both associations and fields, like that:

model = %User{
  __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
  comments: #Ecto.Association.NotLoaded,
  email: "[email protected]",
  first_name: "alex",
  role: #Ecto.Association.NotLoaded
}

How can I get map based on this struct with fields only?

1

1 Answers

23
votes

Ecto defines a __schema__ function for models. So, you can fetch fields using this function:

fields = User.__schema__(:fields)

And then use Map.take/2

Map.take(model, fields)