Having just arrived to Elixir/Phoenix I want to use RethinkDB instead of PostgreSQL but I only find documentation/examples on PostgreSQL (which seems to be the default/official database). There is a very good package from Hamiltop (Rethinkdb-elixir) but unfortunately the documentation in the Wiki is not ready and in the Readme is not enough for me. I absolutely don't want to use SQL (I came from using Meteor/MongoDB where database was not as issue). Can anyone show me a simple example of the code I need to:
This could sound silly but as Meteor took care of these for us, now this is an issue for me...because I'm not being able to do it properly.Thanks!
Step 1) Generate project without ecto:
mix phoenix.new some_app --no-ecto
Step 2) Add rethinkdb as a dependency in mix.exs
defp deps do
[{:phoenix, "~> 0.13.1"},
{:phoenix_html, "~> 1.0"},
{:phoenix_live_reload, "~> 0.4", only: :dev},
{:rethinkdb, "~> 0.0.5"},
{:cowboy, "~> 1.0"}]
end
Step 3) Run mix deps.get
Step 4) Create a database:
defmodule SomeApp.Database do
use RethinkDB.Connection
end
Step 5) Add it to your supervision tree in lib/some_app.ex
- the name
should match your database module above (SomeApp.Database
)
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
# Start the endpoint when the application starts
supervisor(SomeApp.Endpoint, []),
worker(RethinkDB.Connection, [[name: SomeApp.Database, host: 'localhost', port: 28015]])
# Here you could define other workers and supervisors as children
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Rethink.Supervisor]
Supervisor.start_link(children, opts)
end
Step 6) Execute a query:
defmodule Rethink.PageController do
use Rethink.Web, :controller
use RethinkDB.Query
plug :action
def index(conn, _params) do
table_create("people")
|> SomeApp.Database.run
|> IO.inspect
table("people")
|> insert(%{first_name: "John", last_name: "Smith"})
|> SomeApp.Database.run
|> IO.inspect
table("people")
|> SomeApp.Database.run
|> IO.inspect
render conn, "index.html"
end
end
Please note: I have put the queries in the PageController just for the ease of running. In a real example, these would be in separate module - maybe one that represents your resource.
The other thing to note is that I am creating the table inline on the controller. You could execute the command to create a table in a file such as priv/migrations/create_people.exs
and run it with mix run priv/migrations/create_people.exs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With