Get required and optional fields from changeset

script Source

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_fields.

Is there any way we can get @required_fields and @optional_fields from changeset or schema functions?

Thanks

elixirecto

Answers

answered 8 months ago Cyzanfar #1

If you want to add the required and optional field to your changeset cast function this is how you'd do it:

  # using sigils list of words
  @required_fields ~w(field1 field2 field3)
  @optional_fields ~w()

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, @required_fields, @optional_fields)
    |> cast_assoc(:message_details)
  end

From this Elixir Forum post it seems like you can't directly access those required fields. One suggestion would be to create a function or macro that returns these fields:

Update

def required_fields_for model do
  model.__ schema__(:fields)
  |> Enum.filter(fn field -> field in @required_fields end)
end

Given a model this would return the required fields.

comments powered by Disqus