Как выбрать конкретный арендатор после ввода в консоли?

Обновить

April 2019

Просмотры

871 раз

1

Код ниже, хранится в config/initializers/console.rbработах только в первый раз , когда я EXEC rails consoleCLI. При выходе и снова войти, не отображается сообщение выбора, но предварительный просмотр выбранного арендатором загружен.

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

Я хочу каждый раз при входе в rails consoleпопросить то , что арендатор будет загружен.

Спасибо!

4 ответы

2

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.

1

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
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.

1

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

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