script
February 14, 2018, 4:51am
1
I read in Ecto.schema
that we can get the fields
and types
of the fields by doing this:
Model.__ schema__(:fields)
Model.__ schema__(:types)
I have module attribute constant @required_fields and @optional_feilds .
Is there any way I can get required_fields and optional_fields from changeset or schema functions?
Thanks
idi527
February 14, 2018, 7:08am
2
No. But you can filter the values in Model.__ schema__(:fields)
…
Or you can write your own functions or macros to return these fields
def required_fields do
@required_fields
end
Then the filter would work like this
required_fields = Model.required_fields()
Model.__ schema__(:fields)
|> Enum.filter(fn field -> field in required_fields end)
EDIT : ignore me, see the answer below.
2 Likes
Required fields are stored in the :required
field on the Changeset struct:
iex> changeset = Friends.Person.changeset(%Friends.Person{})
iex> changeset.required
[:first_name, :last_name]
you can check all other fields with e.g.:
iex> t Ecto.Changeset.t
@type t() :: %Ecto.Changeset{
action: action(),
changes: %{optional(atom()) => term()},
constraints: [constraint()],
data: Ecto.Schema.t() | map() | nil,
empty_values: term(),
errors: [{atom(), error()}],
filters: %{optional(atom()) => term()},
params: %{optional(String.t()) => term()} | nil,
prepare: [(t() -> t())],
repo: atom() | nil,
repo_opts: Keyword.t(),
required: [atom()],
types: nil | %{optional(atom()) => Ecto.Type.t()},
valid?: boolean(),
validations: [{atom(), term()}]
}
3 Likes
script
February 14, 2018, 10:30am
4
Thanks that helps. Didn’t know that