Not getting right query with Repo.all

Currently, I am searching for those result which has a state set to a particular value. Following is one of the line from my schema result-

state: :private

My Query-

    jobs = JobOpening |> Repo.all(state: String.to_atom(status))

or

    jobs = JobOpening |> Repo.all(state: status)

value in status will be like- public, private, archive (in string)
Whatever value be in my status, this query is fetching all the row(data) from the db? Why is not only fetching those row where status is set to some particular value? Your response will be highly appreciable.

The only option supported in the option list is :prefix. So

jobs = Repo.all(JobOpening)

is always going to return all the records in the entire table. You probably wanted something like:

import Ecto.Query

query =
  from(j in JobOpening, where: j.state == ^status)

jobs = Repo.all(query)
3 Likes

Thanks, but I don’t understand why that one was not working.

Repo.all takes two arguments:

  1. An Ecto query to execute
  2. A list of options. The only supported option is :prefix.

To add a filter, you need to modify the first argument (the query), not the second argument (the list of options) as you were doing.

3 Likes

The 2nd optional argument to Repo.all takes metadata about the query. You need a query that includes a where clause. Another option:

JobOpening |> where(state: ^status) |> Repo.all()
3 Likes