Complex dynamic Ecto query

Hello. I’m stuck on something.

I’m trying to build a dynamic query in Ecto. I would be expecting an array with ids for example: [111, 35]. Then I would be generating a query like this:
select * from brands where id = 111 or id = 35

The thing is I don’t how many ids I will be receiving.

I’m trying to implement something like this:

  def get_brands(ids) do
    query =
      from b in Brand,
        where: format_ids_selection(b),


And then:

# This doesn't work. This is some kind of pseudo-code
defp format_ids_selection(brand, ids) do
    Enum.reduce(ids, "", fn x, acc -> = acc <> " or" end)

Hopefully the idea is well explained and some of you have done something similar and give me an idea.


Changing the where clause in

where: in ^ids

Does that give the wanted result?

1 Like

Yes, it does. Wow, I was overcomplicating myself. Long life to Ecto