Rails - Separate Database per Subdomain

后端 未结 4 1945
逝去的感伤
逝去的感伤 2020-12-07 16:52

I am about to begin writing a Rails application that will allow clients to have a separate subdomain for their access to our application. Thinking from a data security stand

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 17:52

    Off the top of my head you could run a new server instance for each subdomain using different environment.

    But that won't scale very well.

    However the first few google hits for multiple rails databases turn up some new suggestions. Putting together the information in those links provides this wholly untested solution for a single server instance.

    You'll need to add a database entry for each subdomain in your databases.yml. Then add a before_filter to your application controller

    Update! Example reloads the database configurations dynamically. Unfortunately there's no good way to make the update rails wide without messing with your server's internals. So the database configuration will have to be reloaded on every request.

    This example assumes database entries in databases.yml are named after subdomains.

    config/database.yml

    login: &login
      adapter: mysql
      username: rails
      password: IamAStrongPassword!
      host:  localhost
    
    production:
      <<: *login
      database: mysite_www
    
    subdomain1:
      <<: *login
      database: mysite_subdomain1
    
    subdomain2:
      <<: *login
      database: mysite_subdomain2
    ...
    

    app/controllers/application_controller.rb require 'erb' before_filter :switch_db_connection

    def switch_db_connection
      subdomain = request.subdomains.first
      ActiveRecord::Base.configurations = YAML::load(ERB.new(IO.read(Rails.configuration.database_configuration_file)).result)
      ActiveRecord::Base.establish_connection("mysite_#{subdomain}") 
    end
    

    As I said it's completely untested. But I don't foresee any major problems. If it doesn't work hopefully it puts you on the right track.

提交回复
热议问题