步骤 1) 生成没有 ecto 的项目:
mix phoenix.new some_app --no-ecto
步骤 2) 添加 rethinkdb 作为依赖项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
步骤 3) 运行mix deps.get
步骤 4) 创建数据库:
defmodule SomeApp.Database do
use RethinkDB.Connection
end
第 5 步)将其添加到您的监督树中lib/some_app.ex
-name
应该与上面的数据库模块相匹配(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
步骤 6) 执行查询:
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
请注意:我将查询放在 PageController 中只是为了便于运行。在一个真实的例子中,这些将位于单独的模块中 - 也许一个代表您的资源。
另一件需要注意的是,我正在控制器上创建内联表。您可以执行命令在文件中创建一个表,例如priv/migrations/create_people.exs
并运行它mix run priv/migrations/create_people.exs