I have a multi-tenant app in production and I use the default_scope
method described by Ryan Bates in his Railscasts episode.
The real only issue I’ve had so far with this method is people yelling at me for using this method
I bought the book referenced above. It’s gone through a few iterations since I bought it, recommending different approaches through time. I was of some use while I was developing but the version I had spent a great deal of time building a forum gem to actually use the multi-tenant techniques with, which was not of much interest to me, and in fact confused the issue.
The main drawbacks I’ve found with the default_scope
method are (1) in the Rail console you’re always tagging .unscoped
onto everything, this can become a bit cumbersome, and (2) you need to ensure you have a tenant set up in your test_helper since most of your tests will need it. Apart from that it’s been fairly easy going.
The advantages are numerous - the tenant (and therefore default scope) is established as soon as a user signs in, then you don’t have to reference it again in any queries etc. The creation of new records is automatically scoped to the current tenant, very handy. Your models aren’t littered with a lot of conditional scopes for if a user is signed in or not. It’s secure because since there can only be a single tenant there’s no possibility of queries leaking across tenants.
I did look at using PostgreSQL schemas but I was concerned about performance, backups and how to query across schemas for records like User
which need to be queried when there is no-one currently signed in.