jihantoro

jihantoro

Conditional in Ecto.query

my original syntax :

result =
  Enum.map(
    from(Repo, where: ^whitelisted_params)
    |> where([schema], like(schema.nama, ^"#{nama}%"))
    |> limit(^query_limit)
    |> Repo.all(),
    fn elem ->
      elem |> Map.from_struct() |> Map.delete(:__meta__)
    end
  )

i want to add where([schema], like(schema.tgl, ^tgl)) if a conditional are true

tried :

result =
  Enum.map(
    from(Repo, where: ^whitelisted_params)
    |> where([schema], like(schema.nama, ^"#{nama}%"))
    |> (fn(n) -> tgl != "" |> where([schema], like(schema.tgl, ^tgl)) || "" end).()
    |> limit(^query_limit)
    |> Repo.all(),
    fn elem ->
      elem |> Map.from_struct() |> Map.delete(:__meta__)
    end
  )

error :

protocol Ecto.Queryable not implemented for true, the given module does not exist. This protocol is implemented for: Atom, BitString, Ecto.Query, Ecto.SubQuery, Tuple

thank you !

Most Liked

peerreynders

peerreynders

|> (fn(n) -> tgl != "" |> where([schema], like(schema.tgl, ^tgl)) || "" end).()``

looks to me that you were trying to do something like this

|> (fn(query) -> 
     case tgl do
        "" -> query 
        _ -> where(query, [schema], like(schema.tgl, ^tgl))
     end
   end).()
tme_317

tme_317

Whenever I have a conditional in a pipeline (which happens all the time) I just write a separate private function, so in your pipeline it would look like this:

|> maybe_filter_by_tgl(schema, tgl)

Then a separate function:

defp maybe_filter_by_tgl(query, schema, tgl) do
  if tgl != "", do: where(query, [schema], like(schema.tgl, ^tgl)), else: query
end

This is exactly the same as the anonymous function technique from @peerreynders response… for some reason I just find it easier to read (personal preference).

OvermindDL1

OvermindDL1

Yep, this is a pattern I use super often. I keep meaning to find a way to pipeline it better, but I just tend to have long repeated sets of this small ‘mutation’ chunks (copy/pasted from my sources):

    query =
      case refine do
        [pidm: pidm] when is_integer(pidm) -> where(query, [s], s.spriden_pidm == ^pidm)
        [pidm: pidms] when is_list(pidms) ->  where(query, [s], s.spriden_pidm in ^pidms)
        [cnum: cnum] when is_binary(cnum) ->  where(query, [s], s.spriden_id == ^cnum)
        [cnum: cnums] when is_list(cnums) ->  where(query, [s], s.spriden_id in ^cnums)
        [id: id] when is_binary(id) ->        where(query, [s], s.spriden_id == ^id)
        [id: ids] when is_list(ids) ->        where(query, [s], s.spriden_id in ^ids)
        [] -> query
      end

Obviously I don’t use the formatter because it absolutely destroys the readability of these… I wish it could be fixed… :frowning:

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement