Skip to content

Instantly share code, notes, and snippets.

@foeken
Last active June 7, 2016 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foeken/f2244441487caa9cbde3fbe5a76f52bb to your computer and use it in GitHub Desktop.
Save foeken/f2244441487caa9cbde3fbe5a76f52bb to your computer and use it in GitHub Desktop.

Multi tenant Elixir / Phoenix

I'm starting to use Elixir and Phoenix. I want to use a multi-tenant database setup like the Apartment gem provides for Rails apps.

The core setup is this:

  • Request comes in from specific subdomain
  • Translate subdomain to specific tenant database
  • Set the database to the tenant database
  • Do Ecto operations on that database

Now I can achieve this using the prefix option in Ecto:

This would mean I'd build a Plug to convert the domain to a tenant database and then set that somewhere in the conn object. Eventually it will reach the actual controller action and I'd pass that to where I'd want to use the tenant database.

MyApp.Repo.all(%{query | prefix: conn.assigns.tenant.database})

Now here is my Rails mind springing into action: Can I not do this dynamically on a model in some way?

Ecto models support the @schema_prefix option, but could I set that dynamically for a given set of models or is there a more 'Elixir' way to handle such a thing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment