gpt4 book ai didi

elixir - 验证 Elixir Ecto 中的存在,但仅在插入或更新时验证

转载 作者:行者123 更新时间:2023-12-02 07:21:27 25 4
gpt4 key购买 nike

要验证参数是否存在,您可以将字段添加到模型中的 required_fields 模块属性中。然后将其传递给模型的 cast 方法,该方法验证该字段是否存在。

但是,如果您只想验证插入或更新时某些内容是否存在该怎么办?

例如,我只想在记录未保留时验证用户的密码是否存在。换句话说,我不希望用户在编辑帐户信息时必须提供密码。

我想出的最好办法是使用两组不同的必填字段进行更新和插入,然后让一种方法选择合适的字段:

# in changeset method
cast(params, required_fields(model), @optional_fields)

defp required_fields(model) do
if Map.has_key?(model, :id) do
@update_required_fields
else
@insert_required_fields
end
end

这样合理吗,或者有更好的方法吗?

编辑

添加@michalmuskala 的建议以及有关共享变更集功能的后续问题:

def insert_changeset(model, params \\ :empty) do
model
|> cast(params, @insert_required_fields, @insert_optional_fields)
|> shared_changeset
end

def update_changeset(model, params \\ :empty) do
model
|> cast(params, @update_required_fields, @update_optional_fields)
|> shared_changeset
end

defp shared_changeset(changeset) do
changeset
|> validate_password
|> unique_constraint(:email)
end

最佳答案

最简单的解决方案是创建两个变更集函数 - 一个用于插入,一个用于更新。所以你最终会得到类似的结果:

def update_changeset(model, params \\ :empty) do
model
|> cast(params, @update_required_fields, @optional_fields)
end

def insert_changeset(model, params \\ :empty) do
model
|> cast(params, @insert_required_fields, @optional_fields)
end

稍后在 Controller 中,您将调用 Model.update_changeset/2Model.insert_changeset/2<,而不是调用 Model.changeset/2/.

关于elixir - 验证 Elixir Ecto 中的存在,但仅在插入或更新时验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34003292/

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