Search code examples
elixirrethinkdbflash-messagephoenix-framework

How to handle success/error flash messages from Rethinkdb in Phoenix


I'm trying to get the success or insuccess of a query to my RethinkDB in the Phoenix Framework through a Flash message. However I don't know the correct signature to retrieve the result message from RethinkDB in my code block.

def index(conn, _params) do

  #Query that creates a table in the database
    table_create("contentText")
    |> Basedados.Database.run
      # List all elements of a table from the database
    q = table("contentText")
      |> Basedados.Database.run #Run the query through the database
      |> IO.inspect
    conn
    |> put_flash(:error, "Some Message")
    |> put_flash(:info, "Another Message")
    |> render "index.html", contentText: q #Render users searched on the users template
  end

EDIT: Okay I found out that there is supposed to be an errors field along the lines of:

%RethinkDB.Record{data: %{"deleted" => 0, "errors" => 0, "generated_keys" => ["15cc4e19-fc72-4c19-b3a5-47141b6a63e0"], "inserted" => 1, "replaced" => 0, "skipped" => 0, "unchanged" => 0}}

However I don't seem to have it (I tried it like q.errors and q.data.errors) and I get an error every time. The error I'm testing is if the database table does not exist (I change contentText to something else entirely).

I'm able to do some error checking with data:

q = table("contentText")
  |> Basedados.Database.run #Run the query through the database

if is_nil(q.data) do
  conn
  |> put_flash(:error, "Error")
  |> render "index.html", contentText: "failed" #Render users searched on the users template
else
  conn
  |> put_flash(:info, "Sucess")
  |> render "index.html", contentText: q #Render users searched on the users template
end

However this seems like a limited solution as it only detects if there is data in the message. An error can be something else entirely. And since that field seems to count them I would like to get that value and use it in my condition instead (if errors > 0). What do I need to get that field?


Solution

  • use q.data["errors"]) instead of q.data.errors.

    according to the issue hamiltop/rethinkdb-elixir#59, you can use q.data["r"] on failure.