0
votes

I've created a multi-tenant app using apartment and devise gem. Since, I'm using postgresql, apartment gem will create separate schema for each tenant. My database as a few tables, user table is in public namespace whereas pages table is in each tenant specific schema. I'm able to login to each tenant separately and can create separate records for pages table of each tenant.

Now, I want these pages to be accessible in a format like this tenant1.example.com/page-slug-here for this I've following rule in my routes.rb file:

Page.where.not(slug: nil).all.each do |page|
  get "/#{page.slug}", controller: "pages", action: "show", id: page.id
end

These routing rules were working fine when the app was single-tenant but in multi-tenancy it's not working and is throwing "no route matches" error.

My guess here is that the database call in above routing rule is looking in public schema instead of tenant specific schema. How to fix this issue?

1

1 Answers

0
votes

I've solved the issue. The routing code pasted above was copied from a tutorial but it seems the apartment gem doesn't work well with the ActiveRecord native queries in routes.rb file. Apparently, the Page.where()... call was being mapped to public tenant instead of requested tenant at the point of resolving of routes so I've moved the database query from router to controller and in controller the tenant shift was being applied correctly.

I've simplified my routing rule as follows and now it is working and I can find appropriate page by slug in my controller:

get '/:slug' => 'pages#show'