How do I treat records in a tenant as a relationship?

If I have Users and Posts, and Posts are part of the User tenant:

# User
postgres do
  # ...

  manage_tenant do
    template ["user_", :id]
  end
end

# Post
multitenancy do
  strategy :context
end

It wouldn’t make much sense to have a has_many/belongs_to relationship between these two resources, as Posts are inherently part of the User; they live in the User’s schema.

However, you’d miss the user.posts key. Is it possible to have this relationship without needing to (redundantly) adding the relationships and specifying the user_id on the Post?

You can use no_attributes? true on the relationship definition, meaning “all the posts are related”, and then when accessing user and loading data you’d set a tenant which scopes the results to only the relevant posts.

1 Like