basecamp / basecamp/activerecord-tenanted

feature: Easy associations between tenanted and untenanted models

Open
#201 2 comments 5 reactions 0 assignees View on GitHub
Dominant language
Ruby
Stars
617
Forks
29
PR merge metrics
No merged PRs in 30d

Description

(This is probably an advanced feature that does not need to make it into 1.0. I'm just trying to start a conversation and/or nerd snipe people into helping!)

I would like this gem to enhance active record associations to detect if they're between a tenanted model and an untenanted model, and in that case do the extra work to make sure the tenant is respected.

Example: I'm currently building some associations between tenanted and untenanted models. Here's the code I want to be able to write:

```ruby
class User < TenantedRecord
has_one :membership
end

class Membership < UntenantedRecord
belongs_to :user
belongs_to :account # this is also an untenanted model
end
```

and what I want to be able to do is automatically make sure that those associations have the correct scope to be able to retrieve the record in the other database. For example, the manual equivalent of the `has_one` might be something like:

```ruby
class User < TenantedRecord
# add a scope to make sure we only get the Memberships that match the User's tenant
has_one :membership, ->(user) { where(tenant_id: user.tenant) }
end
```

and the `belongs_to` has to look something like:

```ruby
def user
User.with_tenant(tenant_id) { User.find_by(id: user_id) }
end
```

but I would prefer to raise a `WrongTenantError` if the call is in the wrong tenant context.

Some defaults could be assumed, for example the tenant would be determined on the untenanted table by a column named `tenant_id`, which could be overridden with an argument to the association.

Contributor guide

Open the contributing guide

Research direction

No file or test is named; begin by tracing the gem's existing Active Record association handling and tenant-context entry points. Use the User, Membership, and account example to define the supported behavior, including tenant scoping, WrongTenantError handling, and an overridable tenant_id column.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
backend-api-design, databases
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.