我有一个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
答案 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