Elixir 如何在我的模型文件中使用Repo模块
在my标记中型号代码Elixir 如何在我的模型文件中使用Repo模块,elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,在my标记中型号代码 schema "tags" do field :name, :string field :parent, :integer # parent tag id timestamps end def add_error_when_not_exists_tag_id(changeset, params) do tags = Repo.all(Tag) is_exists_tag_id = Enum.reduce(tags, fn(x, acc) -> a
schema "tags" do
field :name, :string
field :parent, :integer # parent tag id
timestamps
end
def add_error_when_not_exists_tag_id(changeset, params) do
tags = Repo.all(Tag)
is_exists_tag_id = Enum.reduce(tags, fn(x, acc) -> acc || (x.id === params.parent) end)
if is_exists_tag_id, do: changeset, else: add_error(changeset, :parent, "not exists parent!")
end
上面的代码导致了下面的错误
(UndefinedFunctionError) undefined function: Repo.all/1 (module Repo is not available)
我能纠正错误吗
标记模型是嵌套的标记模型
标记可以有父标记
最后代码如下。这工作很好 模型中
def add_error_when_not_exists_tag_id(changeset, params, tags) do
is_exists_tag_id = Enum.reduce(tags, false, fn(x, acc) -> acc || (Integer.to_string(x.id) === params["parent"]) end)
if is_exists_tag_id, do: changeset, else: add_error(changeset, :parent, "The tag is not exists.")
end
内部控制器
def create(conn, %{"tag" => tag_params}) do
changeset = Tag.changeset(%Tag{}, tag_params)
|> Tag.add_error_when_not_exists_tag_id(tag_params, Repo.all(Tag))
//
// ...
您不能使用
Repo
变量,因为该变量在此模块中不可用。您需要将其别名为:
alias MyApp.Repo
在控制器中,这是在web.ex
中为您处理的,它在您的模块中通过以下方式调用:
use MyApp.Web, :controller
但是,我强烈建议您避免在模型中使用Repo
。你的模型应该是纯的,这意味着它们不应该有副作用。在模型中调用函数时,对于特定输入应始终具有相同的输出(幂等性)
在本例中,您可以将函数的实现更改为:
def add_error_when_not_exists_tag_id(changeset, params, tags) do
is_exists_tag_id = Enum.reduce(tags, fn(x, acc) -> acc || (x.id === params.parent) end)
if is_exists_tag_id, do: changeset, else: add_error(changeset, :parent, "not exists parent!")
end
您可以在控制器中调用Repo.all
,并将标签传递给函数
如果您有更复杂的行为,请考虑创建<代码> TAGService 模块,使用该函数以及调用<代码> RePo。所有
谢谢您的详细解答!我将尝试写入验证逻辑。因为,到目前为止,我还没有标签模型的其他逻辑。哎呀,我犯了一个错误。。。我将尝试将纯逻辑写入tag.ex
函数,并从控制器调用该函数。我明白了changeset=Tag.changeset(%Tag{},Tag_params)|>Tag.add_error_当不存在时_Tag_id(Tag_params)