cjm2671
cjm2671

Reputation: 19496

Eval-ing paramaters in Elixir (with Ecto)

Have a look at the select() line below:

def query_group(user, group_by, filters \\[]) do
    from(Click)
    |> select([c], {c.^group_by, count(c)})
    |> where([c], c.link_user_id == ^user.id)
    |> where([c], ^filters)
    |> group_by([c], ^group_by)
    |> Repo.all
    |> Enum.map(&(Tuple.to_list &1))
  end

group_by is an atom. For example, if group_by = :platform, then in the select field, I need to get select([c], {c.platform, count(c)}).

What's the best way of approaching this?

Upvotes: 2

Views: 48

Answers (2)

m3characters
m3characters

Reputation: 2290

You can also use field/2, as in select([c], {field(c, ^group_by), count(1)}) (not sure group_by needs to be pinned here but I think so)

Upvotes: 1

Máté
Máté

Reputation: 2345

You can use fragments for this, changing the select bit to

...
|> select(fragment("count(*), ?", ^group_by))

This way you can use the input of the function easily.

Upvotes: 0

Related Questions