Last active
September 25, 2022 19:56
-
-
Save fabianhjr/bbc4ebf6b5811a9b3ecf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create(conn, %{"stress" => stress_params}) do | |
changeset = Stress.changeset(%Stress{}, stress_params) | |
IO.inspect stress_params | |
{long, lat, type} = {stress_params["long"], stress_params["lat"], stress_params["type"]} | |
q = from p in Plataforma.Average, | |
select: p, | |
where: p.long == ^long and p.lat == ^lat and p.type == ^type | |
average = Repo.all(q) |> first_or_create | |
average_params = %Plataforma.Average{"long" => stress_params["long"], | |
"lat" => stress_params["lat"], | |
"type" => stress_params["type"], | |
"stress" => average[:stress] * (average[:samples]) / (average[:samples] + 1) + stress_params["stress"] / (average[:samples] + 1), | |
"samples" => average[:samples] + 1} | |
average_cs = Average.changeset(average, average_params) | |
case Repo.insert(changeset) do | |
{:ok, stress} -> | |
Repo.insert(average_cs) | |
conn | |
|> put_status(:created) | |
|> put_resp_header("location", stress_path(conn, :show, stress)) | |
|> render("show.json", stress: stress) | |
{:error, changeset} -> | |
conn | |
|> put_status(:unprocessable_entity) | |
|> render(Plataforma.ChangesetView, "error.json", changeset: changeset) | |
end | |
end | |
defp first_or_create([]) do %Plataforma.Average{stress: 0.5, samples: 0} end | |
defp first_or_create([x|_]) do x end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
== Compilation error on file web/controllers/stress_controller.ex == | |
** (CompileError) web/controllers/stress_controller.ex:21: unknown key "long" for struct Plataforma.Average | |
(elixir) src/elixir_map.erl:182: :elixir_map."-assert_struct_keys/5-lc$^0/1-0-"/5 | |
(elixir) src/elixir_map.erl:59: :elixir_map.translate_struct/4 | |
(elixir) src/elixir_clauses.erl:36: :elixir_clauses.clause/7 | |
(elixir) src/elixir_def.erl:178: :elixir_def.translate_clause/7 | |
(elixir) src/elixir_def.erl:167: :elixir_def.translate_definition/8 | |
(elixir) src/elixir_def.erl:82: :elixir_def.store_definition/9 | |
web/controllers/stress_controller.ex:13: (module) | |
(stdlib) erl_eval.erl:657: :erl_eval.do_apply/6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment