I am a beginner in elixir/phoenix. I am adding into a project that someone else has started.
I am trying to create a psql to json application with an existing psql database.
I create the files by running the command: mix phx.gen.json
But I did not do a mix ecto.migrate
When I am trying to get the json of a record from the database, I am getting the error below:
[info] GET /assignments/01
[debug] Processing with ApiWeb.AssignmentsController.show/2
Parameters: %{“id” => “01”}
Pipelines: []
[debug] QUERY OK source=“assignments” db=3406.0ms queue=47.0ms idle=63.0ms
SELECT a0.“id”, a0.“airline” FROM “assignments” AS a0 WHERE (a0.“id” = $1) [01]
[info] Sent 404 in 3578ms
[debug] ** (Ecto.NoResultsError) expected at least one result but got none in query:
I tried testing old existing routes, which is created by another person, that queries a record from another table and that is working just fine.
I have worked on a project from scratch using mix phx.gen.json along with mix ecto.migrate. And this worked.
I wonder if it’s because I skipped ecto.migrate this time since there is an existing table? How do I create schemas and files to handle json for an existing psql table?
This doesn’t look like a setup problem, it looks like a data problem - there’s no row in assignments with that ID, so calling Repo.one() fails with NoResultsError.
Would there be a difference between running and not running the command: mix ecto.migrate
I know that command is normally ran to create the database table based on the schema. But what if you are using an existing db table?
kokolegorille,
Here is the schema:
defmodule Api.Assignment do
use Ecto.Schema
import Ecto.Changeset
schema “assignments” do
field :airline, :string
end
@doc false
def changeset(assignment, attrs) do
assignment
|> cast(attrs, [:airline])
|> validate_required([:airline])
end
end
Here is show from AssignmentsController:
def show(conn, %{“id” => id}) do
assignment = Assignments.get_assignment!(id)
render(conn, “show.json”, assignment: assignment)
end
And get_assignment from Assignments:
def get_assignment!(id), do: Repo.get!(Assignment, id)
Eiji,
Sorry, I meant it to be 1. I tried the API again /assignments/1 and still same error.