Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional class inheritance for rails model

I have a multi-tenant rails app up and running. Models that i want scoped to the current tenant (like this article model here) inherit the tenantscoped model like this

class Article < TenantScoped

end

this works great. i only recieve objects scoped to the current tenant.

but now im creating an admin interface where i want to be able to add articles to all tenants. but my admin interface is acting as a tenant and the models are being scoped to it. Which ends with no entries being shown.

I am proposing that the best solution to this is to conditionally inherit from the tenant scoped model like this

class Article

  unless SudoTenant.current?
    < TenantScoped
  else
    < ActiveRecord::Base
  end

end

i've been searching around to conditional inheritance for ruby classes and havent found anything yet. my syntax is wrong here or is this even possible?

Thanks in advance

like image 682
ben.m Avatar asked Feb 17 '26 07:02

ben.m


1 Answers

You can define the class using the block syntax:

if SudoTenant.current?
  Article = Class.new(ActiveRecord::Base) do
    # your code
  end
else
  Article = Class.new(TenantScoped) do
    # your code
  end
end

I strongly recommend to use mixins instead of conditionally inheriting, it's cleaner, clearer and more obvious.

like image 141
Federico Builes Avatar answered Feb 18 '26 20:02

Federico Builes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!