4

The code below, stored at config/initializers/console.rb works only at first time I exec rails console CLI. When exit and enter again, no selection message is displayed, but the preview tenant selected is loaded.

if defined?(Rails::Console) || $PROGRAM_NAME.include?('spring')
  tenants = Apartment.tenant_names.sort
  default = tenants.first

  puts "Available tenants: #{tenants.join(', ')}"

  print "Select tenant (#{default}): "
  tenant = gets.strip

  Apartment::Tenant.switch! tenants.include?(tenant) ? tenant : default
end

I wish every time when enter at rails console ask for what tenant will be loaded.

Thanks!

Bruno Wego
  • 2,099
  • 3
  • 21
  • 38
  • 1
    It's works in my case. Rails version? – Mauro Nov 24 '17 at 15:47
  • Your proposed solution worked for me once I removed gem `spring` from my project. The Rails maintainers excluded `spring` from rails 7 as the speed benefits are negligible for modern computers: https://weblog.rubyonrails.org/2021/9/15/Rails-7-0-alpha-1-released/#a-few-other-highlights – Milos Blasko Oct 06 '21 at 10:53

4 Answers4

5

The only way I could get Apartment::Tenant.switch! to work in the Rails console was by creating the following .irbrc file in the project's root directory:

IRB.conf[:IRB_RC] = Proc.new do
  tenants = Apartment.tenant_names.sort
  puts "Available tenants: #{tenants.join(', ')}"

  print "Select tenant: "
  tenant = gets.strip

  unless tenant.empty?
    if tenants.include?(tenant)
      Apartment::Tenant.switch!(tenant)
    else
      puts "Tenant not found in list '#{tenant}'"
    end
  end
  puts "Tenant set to '#{Apartment::Tenant.current}'"
end
joshudev
  • 136
  • 3
  • 3
  • Check this for `pry` version https://stackoverflow.com/questions/53251640/apartmenttenant-switch-during-bin-rails-console-using-pry – Ram on Rails Nov 11 '18 at 18:10
4

I faced similar issue. If you are using the Apartment Gem. In your rails console you can switch between tenants by first connecting to DB and then using schema_search_path

e.g.
c = Company.connection
c.schema_search_path = "tenant1"

To check tenant has been switched use ActiveRecord::Base.connection.schema_search_path

=> "\"tenant1\""

Company is just a table in my DB.

Abdullah Aden
  • 882
  • 9
  • 13
1

Here is a simple code (pry version) usable at launch or while at console

`Apartment::Tenant.switch!` during `bin/rails console` using `pry`

Ram on Rails
  • 1,299
  • 11
  • 25
0

This happens because of Spring, by default it's configured only for the development environment. Just remove it from your Gemfile and it should work as you expected.