gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:26:17 25 4
gpt4 key购买 nike

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

最佳答案

使用 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

关于elixir - 如何验证 ecto 中指定关联的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40436686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com