Search code examples
elixirphoenix-frameworkecto

How do I generalize this Ecto/Elixir function?


I've got the following, which applies a WHERE statement to an ecto query if platform exists.

  defp maybe_platform(queryable, false), do: queryable
  defp maybe_platform(queryable, platform) do
      queryable
      |> where([c], c.platform == ^platform)
  end

How can I generalise this code for any variable (instead of just platform)? (it's the c.platform bit I'm struggling with)


Solution

  • You need to use Ecto field https://hexdocs.pm/ecto/Ecto.Query.API.html#field/2

    Your function would look something like this

    defp maybe_field(queryable, field_name, field_value) do
        queryable
        |> where([c], field(c, ^field_name) == ^field_value)
    end
    

    and then

    (from m in MyModel)
    |> maybe_field(:platform, "platform_name_or_variable")
    |> maybe_field(:another_field, "some value")
    |> maybe_field(:is_platform_enabled, true)
    |> Repo.all