I'm working on a multi-tenant application via the Apartment gem. Everything is working perfectly, but I'm curious about something. How would one go about updating a record for a given tenant in the rails console?
For example, If I do the following it works as you'd expect (without apartment of course):
@alerts = Alert.create(name "blah", date_triggered: "blah", etc..)
How would you do that with tenants? The code below doesn't work, which isn't a surprise. I'm just not sure how you'd accomplish this easily within the console.
@alerts = tenant01.Alert.create()
Alerts is within the scope of the tenant so each tenant would have their own alerts. This is 100% working if I use the browser for adding / modifying the records, I'm just not entirely sure how to translate the sql back into a rails command and test via the console.
Any ideas, or thoughts would be greatly appreciated.
As far as I know, there are two ways to accomplish this.
For example,
Apartment::Tenant.switch('tenant_name') do
@alerts = Alert.create(name "blah", date_triggered: "blah", etc..)
end
By default, the rails console will query from the public schema. Check Apartment::Tenant.current
to get the tenant that rails uses to query the data from.
After the execution of the code block the rails console will switch back to public schema.
Apartment::Tenant.switch!('tenant_name')
Then, @alerts = Alert.create(name "blah", date_triggered: "blah", etc..)
Or do whatever.
Then the rails console will be switched to a specific tenant, we have to manually switch the tenant based on the needs.