如何在ecto中验证指定关联的长度?

时间:2016-11-05 09:31:49

标签: elixir ecto

我有一个many_to_many关联的ecto模型。我通过put_assoc将几个关联模型放到变更集中,并希望验证相关模型的数量。我怎样才能做到这一点?示例模型:

defmodule Content do
  use MyApp.Web, :model

  many_to_many :topics, MyApp.Topic,
    join_through: MyApp.ContentTopic,
    on_replace: :delete

  def changeset(struct, params \\ %{}) do
    topics_changesets = Map.get(params, "topics", [])
      |> Enum.map(fn(t) -> change(t) end)

    struct
    |> cast(some_cast_here)
    |> put_assoc(:topics, topics_changesets)
    |> I want to validate minimum and maximum amount of assigned topics here. How can I do that?
  end
end

1 个答案:

答案 0 :(得分:3)

使用validate_length

def changeset(struct, params \\ %{}) do
  # ...

  struct
  |> cast(your_cast_here)
  |> put_assoc(:topics, topic_changesets)
  |> validate_length(:topics, min: @min_topics, max: @max_topics)
end