Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch only fields from ecto model?

Tags:

elixir

ecto

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?

like image 970
asiniy Avatar asked Sep 21 '16 15:09

asiniy


1 Answers

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)
like image 141
asiniy Avatar answered Nov 06 '22 01:11

asiniy