步骤1)生成没有ecto的项目:
mix phoenix.new some_app --no-ecto
第二步) 在mix.exs
中添加rethinkdb作为依赖项
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 = [
supervisor(SomeApp.Endpoint, []),
worker(RethinkDB.Connection, [[name: SomeApp.Database, host: 'localhost', port: 28015]])
]
opts = [strategy: :one_for_one, name: Rethink.Supervisor]
Supervisor.start_link(children, opts)
end
第六步) 执行查询:
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
运行它。