Created
August 18, 2015 13:29
-
-
Save svoboda-jan/021cd215061325ec05be to your computer and use it in GitHub Desktop.
Very simple multi-tenancy for Rails (shared database)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module TenantModel | |
def self.included(base) | |
base.extend ClassMethods | |
base.instance_eval do | |
acts_as_tenant | |
end | |
end | |
class InvalidTenant < SecurityError; end | |
module ClassMethods | |
def acts_as_tenant | |
default_scope -> { where(tenant_id: Tenant.current.id) } | |
belongs_to :tenant | |
validates_presence_of :tenant_id | |
before_validation(:on => :create) do |obj| | |
obj.tenant = Tenant.current | |
end | |
before_save do |obj| | |
obj.tenant = Tenant.current | |
end | |
before_update do |obj| | |
raise TenantModel::InvalidTenant unless obj.tenant == Tenant.current | |
end | |
before_destroy do |obj| | |
raise TenantModel::InvalidTenant unless obj.tenant == Tenant.current | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment