Elixir,Ecto模式匹配条件与db查询的行为不符合预期

编程入门 行业动态 更新时间:2024-10-08 13:32:06
本文介绍了Elixir,Ecto模式匹配条件与db查询的行为不符合预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果该记录不存在,我希望此条件可以创建它,但是它不....返回nil。

If the record does not exist, I would expect this conditional to create it, but it does not.... nil is returned.

case Repo.get_by(User, %{email: "hulk@hogan"}) do struct -> struct nil -> params = Map.merge(%{email: "hulk@hogan"}, %{password: "password"}) Repo.insert!(User.changeset(User.__struct__, params)) end # returns nil.... huwutt???

但是,如果我更改条件的顺序,它就可以工作。我在这里想念什么?

However, if I change the ordering of the condition, it works. What am I missing here?

case Repo.get_by(User, %{email: "hulk@hogan"}) do nil -> params = Map.merge(%{email: "hulk@hogan"}, %{password: "password"}) Repo.insert!(User.changeset(User.__struct__, params)) struct -> struct end # returns a set of 24" pythons, brother.... huzah!

推荐答案

根据文档

案例case allows us to compare a value against many patterns until we find a matching one:

在另一个模式中单词,第一个匹配的案例将运行,而 case 不会继续进行。

In another word, the first matching case will run and case will not proceed further.

在您的第一个示例中,第一个因为您不提供任何保护,所以大小写总是匹配的,因此 struct 将绑定到 nil 。第二种方法解决了问题,因为您首先要对特定情况进行模式匹配,然后通过将 case 的求值绑定到 struct来默认为一般情况。

In your first example, the first case will always be matched since you are not providing any guards, and as such, struct will bind to nil. Your second approach solves the problem because you're pattern matching a specific case first, and then defaulting to a general case by binding the evaluation of case to struct.

还请注意,您可以使用gua rds在您的第一种情况下,请确保 struct 的值是 map 的此处。

Also note that you can use guards in your first case to make sure that the value of struct is a map as outlined here.

case Repo.get_by(User, %{email: "hulk@hogan"}) do struct when is_map(struct) -> struct nil -> params = Map.merge(%{email: "hulk@hogan"}, %{password: "password"}) Repo.insert!(User.changeset(User.__struct__, params)) end

更多推荐

Elixir,Ecto模式匹配条件与db查询的行为不符合预期

本文发布于:2023-11-25 10:17:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629360.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不符合   条件   模式   Elixir   Ecto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!