ErwinM / acts_as_tenant

Easy multi-tenancy for Rails in a shared database setup.
MIT License
1.53k stars 262 forks source link

Enabling eager_loading causes NoTenantSet error #318

Closed drale2k closed 7 months ago

drale2k commented 9 months ago

Hi, i am running into an issue with ActsAsTenant, which throws an ActsAsTenant::Errors::NoTenantSet error when booting the rails server, but only in production. The reason seems to be eager loading. It breaks on the following validation:

validates :inbox_simcard_id, inclusion: { in: InboxSimcard.available.ids, message: "That Simcard is already taken" }

It seems to break when trying to access InboxSimcard. When i set config.eager_loading = false it works but i don't want to do that in production.

I understand that it expects a tenant to be set during runtime, but on server boot? How am i supposed to set a tenant when the app is just booting?

drale2k commented 9 months ago

I was able to work around it refactoring my validation to not use a class and scope but an instance method instead, which performs the access via an association over the Account model.

My guess is using an association fixed it since it can now go through the Account and therefore acts_as_tenant() is satisfied.

I will leave this issue open because i would like to know if this is a bug with ActsAsTenant or is that just the way it is with ActsAsTenant and you can't use scopes on a model which has acts_as_tenant set.

I was banging my head for a day over this. For anyone else running into this issues, i went from:

validates :inbox_simcard_id, inclusion: { in: InboxSimcard.available.ids, message: "That Simcard is already taken" }

to:

validate :simcard_cannot_be_taken

def simcard_cannot_be_taken
  unless inbox_simcard_id.in?(account.inbox_simcards.available.ids)
    errors.add(:inbox_simcard_id, "That Simcard is already taken")
  end
end
excid3 commented 7 months ago

Your original validation would have cached the ids on app boot, which is probably not what you wanted.

drale2k commented 7 months ago

Oh wow, didn't know that. So by accident i solved that one as well. Learned something thanks!