我有一个具有关联的 ecto 模型many_to_many。我通过将几个关联模型放入变更集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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)