如何在我的模型文件中使用Repo模块

2YY*_*2YY 12 elixir ecto phoenix-framework

在我的Tag模型代码中

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
Run Code Online (Sandbox Code Playgroud)

上面的代码导致下面的错误.

(UndefinedFunctionError) undefined function: Repo.all/1 (module Repo is not available)
Run Code Online (Sandbox Code Playgroud)

我可以修复错误吗?

Tag模型是嵌套标签模型.

标签可以有父标签.


最终代码如下.这很好.

在模型中

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
Run Code Online (Sandbox Code Playgroud)

在控制器中

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))
  //
  // ...
Run Code Online (Sandbox Code Playgroud)

Gaz*_*ler 20

您无法使用Repo此模块中不可用的变量.你需要别名:

alias MyApp.Repo
Run Code Online (Sandbox Code Playgroud)

在控制器中,这是为您处理的,web.ex在您的模块中调用它:

use MyApp.Web, :controller
Run Code Online (Sandbox Code Playgroud)

但是,我强烈建议您避免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
Run Code Online (Sandbox Code Playgroud)

您可以调用Repo.all控制器并将标记传递给该函数.

如果您有更复杂的行为,请考虑创建一个TagService使用该函数以及调用该函数的模块Repo.all