Search code examples
postgresqlelixirecto

Joining associations in polymorphic schemas


the problem I am facing right now is handling associations in polymorphic schemas.

Let's say I've got such a problem to solve:

  • I've got multiple organizations.
  • Each organization must have its own table of users.
  • Each organization must have its own table of events.
  • User has many events // event belongs to the user.

The way I think it should work is that once the organization is created a trigger on the database is launched and it creates users and events tables for this organization. The users and events tables are created with a somehow logically generated name, so they are easy to refer to. From the Elixir perspective there is one polymorphic schema for events and one for users.

Referring to the users and events tables in queries, as to the separate entities, is quite easy and seems more or less like below.

(from user in {table_name, User}, as: :user)
...
(from event in {table_name, Event}, as: :event)

User schema itself is a polymorphic schema, Event schema too. Normally, without polymorphic tables, joins would be simple. The problem for me is if is it possible in the polymorphic User schema to refer to the polymorphic Event schema with the has_many association? Is it handled "out of the box" and it just need to refer to the Event schema like: has_many :events, Event, on_delete: :delete_all and I can use joins in queries on top of that without any trouble?

If someone could explain to me how is it handled I would be really grateful :)


Solution

  • {"users_1", User}|> join(:left, [u], e in {"events_1", Event}) |> preload([u, e], events: e) |> Repo.all
    

    you can replace schema atom (e.g. User) with tuple ({table_name, schema_atom})