Ecto 中的插值字段如何查询?

How do interpolation fields in Ecto queries?

Ecto documentation 显示了如何进行插值。但是我的查询中需要动态字段。我有几十个字段,为每个字段编写查询似乎没有凝聚力。

defmodule Hedone.SearchController do
  use Hedone.Web, :controller

  alias Hedone.User

  def idade(conn, %{"idade+" => maior, "idade-" => menor, "campo" => campo}) do
    IO.inspect campo
  query = from u in User, where: u.campo > ^maior and u.campo < ^menor, select: u.name
  pesquisa = Repo.all query
  IO.inspect pesquisa
  text conn, "Works"
end

end

此控制器生成以下错误:

** (Ecto.QueryError) web/controllers/search.ex:8: field `Hedone.User.campo` in `where` does not exist in the schema in query:

from u in Hedone.User,
  where: u.campo > ^18 and u.campo < ^40,
  select: u.name

自动翻译。

我假设 campo 包含一个字符串,其中包含您要使用的字段的名称,例如"age"。您可以在查询中使用 field

def idade(conn, %{"idade+" => maior, "idade-" => menor, "campo" => campo}) do
  campo = String.to_existing_atom(campo)
  query = from u in User, where: field(u, ^campo) > ^maior and field(u, ^campo) < ^menor, select: u.name
  pesquisa = Repo.all query
  IO.inspect pesquisa
  text conn, "Works"
end

field 期望该字段是一个原子,所以我使用 String.to_existing_atom 将字符串安全地转换为原子。由于您必须已经在模型的架构中定义了字段,因此 String.to_existing_atom 不会因任何有效的字段名称而失败。

我将此作为解决该问题的另一种方法的示例发布。人们可能会使用宏来处理这种转换,因为宏是在编译时解析的:

defmacro idade(conn, formula, campo: binding) do
  q = formula |> String.replace "campo", binding
  quote do
    from u in User, where: unquote(q), select: u.name
      |> Repo.all
    text conn, "Works"
  end
end

并这样称呼它:

idade(nil, "u.campo > ^maior and u.campo < ^menor", campo: "age")