DEV Community

A Rails Multi-Tenant Strategy That's ~30 Lines and "Just Works"

Jason Meller on November 09, 2021

When engineering a new SaaS app, how you plan to handle customer data tenancy is usually one of the first decisions you and your team will need to ...
Collapse
 
bobbymcwho profile image
Bobby McDonald

Should this

# spec/spec_helper.rb
config.before(:all) do
  Current.reset
end
Enter fullscreen mode Exit fullscreen mode

be

# spec/spec_helper.rb
config.before(:each) do
  Current.reset
end
Enter fullscreen mode Exit fullscreen mode

?

Collapse
 
terracatta profile image
Jason Meller Kolide

You are correct! Fixed.

Collapse
 
apaciuk profile image
Paul Anthony McGowan • Edited

Awesome, am borrowing (stealing, whatever) it for Rails 7 Jumpstart themes at

github.com/xhostcom/rails-jumpstar...

Muchos Gracias, and may the forces of evil become extremely confused on the way to your house.

Collapse
 
ghepting profile image
Gary Hepting

Nice write up!

Collapse
 
ghiculescu profile image
Alex Ghiculescu

Since github.com/rails/rails/pull/46522 you don't need the optional: true

Collapse
 
apaciuk profile image
Paul Anthony McGowan

One thing though if the new user has not signed up yet, can not set an account, or account_id, get error You must set an account with Current.account=

Needs workaround for that.

Collapse
 
codingbyharry profile image
Harry

Two possible options to consider:

  1. Create the tenant before the user so that the resource exists
  2. Don't use the concern on the user model and add a belongs_to :account, optional: true. Then probably want validations to ensure an account always exists on update.
Collapse
 
kirantpatil profile image
kirantpatil

Hello,

Any further updates on scaling multi tenant ?

Collapse
 
bestfriend101 profile image
BestFriend101

Don't forget to check out github.com/ErwinM/acts_as_tenant 👍

Collapse
 
ashwin47 profile image
Ashwin M

After including the concern i cant even initialise my registration form because it raises Current::MissingCurrentAccount.

Is there a way around it?

Collapse
 
macedo profile image
Rafael Macedo

Do you use factory_bot for testing? How do you manage it in your test suite?