1

How can I seed a new tenant in a multi-tenant app that uses the Apartment gem for scoping?

I added the following to seeds.rb but it doesn't seem to work with apartment:

tenants = Tenant.create([
{
  name: 'User1',
  domain: 'user1'
},
{
  name: 'User2',
  domain: 'user2'
}
])

Even is the database is blank, seeds.rb tries to create the schema twice and fails with this error when I do rake db:seed:

Apartment::TenantExists: The schema user1 already exists.
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Jacob
  • 6,317
  • 10
  • 40
  • 58

1 Answers1

4

Rails rake runs tasks for each tenants/schemas your are trying to create. So run your creation or seeding tasks by first checking if the current schema is a public.

Something like this would do.

if Apartment::Tenant.current == 'public'
  Apartment::Tenant.create('tenant1')
  Apartment::Tenant.create('tenant2')
end
bir_ham
  • 513
  • 5
  • 19