Add a where to a query depending on condition

Hi, me again.

I got the following code:

updated_at = Map.get(params, "updated_since", "1970-01-01T12:00:00")
query =
  from m in ChatMessage,
  join: u in assoc(m, :chat_user),
  order_by: [asc: m.updated_at],
  where: u.chat_id ==^ id,
  where: m.updated_at > ^updated_at

I added the parameter updated_since as optional parameter to some api calls.
I don’t want to use Map.get in all controllers and added a methode for this:

def check_updated(query, params) do
    case Map.get(params, "updated_since") do
        nil -> query 
        updated_since -> query |> where(updated_at: > ^updated_since)

I get a SyntaxError and think this is wrong anyway.
What would be the right way to implement a method to extract
where: xyz.updated_at > ^updated_at
to a central method?


Please show the full error.

== Compilation error on file web/controllers/chat/chat_message_controller.ex ==
** (SyntaxError) web/controllers/chat/chat_message_controller.ex:27: syntax error before: '>'
(elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

Don’t think this will help since my approach is wrong.

That’s probably the offender

It always helps :slight_smile: Any time there’s an error always just include the error.

Oops, had my > not included in updated_at: ^updated_since, sorry. Updated it in my post.

def check_updated(query, %{"updated_since" => updated_since}) do
  where(query, [q], q.updated_at > ^updated_since)
def check_updated(query, _), do: query

Thanks a lot, this made the magic I needed :slight_smile:

1 Like