ruby-on-railsmulti-tenantrake-taskapartment-gem

Running custom rake task for multi tenant app rails


I have a custom rake task

namespace :abc do

  desc "seeds abc to a database" do

    task seed_abc: :environment do

      Tenant.find_each do |tenant|

        puts "Running task for tenant#{tenant.name}"
        Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].sort.each do |filename|

        p "Seeding #{filename}"
        load(filename) if File.exist?(filename)
      end
    end
  end
end

when i run rake task its only seeded in default tenant, but while seeding i can see

Running task for tenant abc "Seeding /path...../path/filename.rb" "Seeding /path...../path/filename.rb" Running task for tenant xyz "Seeding /path...../path/filename.rb" "Seeding /path...../path/filename.rb" Running task for tenant 123 "Seeding /path...../path/filename.rb" "Seeding /path...../path/filename.rb"

But when i check in console, its only seeded for default tenant, How do i seed for all the tenannts ?


Solution

  • I know this is a few months old, but thought I'd help for future people.

    With Apartment, the cleaner way to do this to make sure the tenant switches back to public after the block is to do the following:

    Apartment::Tenant.switch(tenant.name) do
      #Your code in this block.
    end
    

    It is important to make sure it switches back because if it doesn't, you could end up running code on the wrong tenant.

    If you do as you suggested above Apartment::Tenant.switch!(tenant.name) the tenant stays selected until you switch it again. If the next switch fails, it stays on the current tenant and executes the code on the wrong DB.