Ecto Recent association with has_many filtering

So from the docs, it is now possible to add criteria over :has_many associations: https://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3-filtering-associations

Now I have this association:

has_many(:ideas, Idea, on_replace: :nilify)

And I would like to have

has_many(:recent_ideas, Idea, where: [???]) # inserted_at > (Date.utc_today() |> Date.add(-15))

I’m struggling with the syntax and the doc. Anyone can help?

Thanks

:wave:

Maybe

has_many(:recent_ideas, Idea, where: [inserted_at: {:fragment, "? > now() - interval '15 days'"}])

if you are on postgres.

3 Likes

Amazing! Thanks

It even works with:

    from(d in Person,
      join: s in assoc(d, :recent_ideas)
    )
1 Like