Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto - validate presence of associated model

How can one validate the presence of an associated model in Ecto ?

schema "foo" do
  has_many: bar, Bar

  timestamps
end

@required_fields ~w(bar) # invalid

Is there a way to do so ? And validate a min/max number of these fields ?

like image 360
Kernael Avatar asked Jun 26 '15 12:06

Kernael


1 Answers

There isn't anything yet. But you can run these validations yourself in your changeset function:

def changeset(model, params) do
  model
  |> cast(...)
  |> validate_bar_association()
end

def validate_bar_association(changeset) do
  bar = changeset.model.bar
  cond do
    bar == nil ->
      add_error changeset, :bar, "No bar"
    length(bar) < 5 ->
      changeset
    true ->
      add_error changeset, :bar, "waaaay too many"
  end
end

We do want to make nested associations better but there are other items higher up on our priority list. :)

like image 97
José Valim Avatar answered Nov 10 '22 08:11

José Valim