9

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 Answer 1

25

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)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.