Get schema prefix from Ecto.Schema.Metadata

I am trying to get the schema prefix from user inserted into a prefixed schema and use it for another repo insert.

  def register_user(attrs, org) do
    tenant = org.tenant.slug
    %User{}
    |> Ecto.put_meta(prefix: tenant)
    |> User.registration_changeset(attrs)
    |> Repo.insert()
  end

returns:

#MyApp.Accounts.User<
  __meta__: #Ecto.Schema.Metadata<:loaded, "site-1", "users">,
  confirmed_at: nil,
  email: "user@example.com",
  hashed_password: "$2b$12$4kRR67ZW7Pvw8rnS9c1p1uOq6cbvskliCGZWXMXxlwZ3hozD7BmT.",
  id: 1,
  inserted_at: ~N[2020-07-02 09:51:33],
  updated_at: ~N[2020-07-02 09:51:33],
  ...
>

I am trying to get the value site-1 from meta_: #Ecto.Schema.Metadata<:loaded, “site-1”, “users”>.

I think that MyApp.Accounts.User.__schema__(:prefix) will do the job for you.
source: https://hexdocs.pm/ecto/Ecto.Schema.html#module-reflection

Thanks for the link.

" __schema__(:prefix) - Returns optional prefix for source provided by @schema_prefix schema attribute;"

The value is set on a previous insert, so the value returns nil. (I updated the post with the code with Ecto.put_meta).

I am getting closer though…

Ahh of course there is a Ecto.get_meta if there is a Ecto.put_meta

tenant = Ecto.get_meta(user, :prefix)
1 Like