ECTO-验证关联模型的存在 [英] Ecto - validate presence of associated model
本文介绍了ECTO-验证关联模型的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何验证Ecto中相关模型的存在?
How can one validate the presence of an associated model in Ecto ?
schema "foo" do
has_many: bar, Bar
timestamps
end
@required_fields ~w(bar) # invalid
有办法吗?并验证这些字段的最小/最大数量?
Is there a way to do so ? And validate a min/max number of these fields ?
推荐答案
还没有任何东西.但是您可以在changeset
函数中自己运行这些验证:
There isn't anything yet. But you can run these validations yourself in your changeset
function:
def changeset(model, params) do
model
|> cast(...)
|> validate_bar_association()
end
def validate_bar_association(changeset) do
bar = changeset.model.bar
cond do
bar == nil ->
add_error changeset, :bar, "No bar"
length(bar) < 5 ->
changeset
true ->
add_error changeset, :bar, "waaaay too many"
end
end
我们确实想使嵌套关联更好,但是优先级列表中还有其他更高的项. :)
We do want to make nested associations better but there are other items higher up on our priority list. :)
这篇关于ECTO-验证关联模型的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文