Using my own function in "where(...)" ---> is not a valid query expression

I have this query which works:

  import Ecto.Query

  where(Article, [a], x.status == "active")

Whereas this doesn’t:

  # 1
  where(Article, [a], Article.active?(a))

  # 2
  where(Article, [a], Article.active?(a) == true)

Error:

Article.active?(x) is not a valid query expression.

active? defined as:

      def active?(a) do
        a.status == "active"
      end

How to make it work?

Ecto allows a limited set of expressions inside queries. […]
You can find the full list of operations in Ecto.Query.API .

Ecto.Query.API

Lists all functions allowed in the query API.

This means: you can’t.

3 Likes

You can make it a macro.

defmacro active?(a) do
  quote do: unquote(a).status == "active"
end
3 Likes