Automatically switching databases from rails app gracefully from ApplicationController?

I saw this post several times, but actually did not find the answer to this specific question.

I would like to run a rails application based on a detected .host request (imagine that I have two subdomains pointing to the same rails application and the server ip address: myapp1.domain.com and myapp2.domain.com).

I am trying to use myapp1 for the default database "production", and myapp2 queries always use an alternative remote database. Here is an example of what I was trying to do in an application controller that didn't work:

class ApplicationController < ActionController::Base
  helper :all 
  before_filter :use_alternate_db

  private

    def use_alternate_db

      if  request.host == 'myapp1.domain.com'
        regular_db
      elsif request.host == 'myapp2.domain.com'
        alternate_db
      end

    end

    def regular_db
      ActiveRecord::Base.establish_connection :production
    end

    def alternate_db
      ActiveRecord::Base.establish_connection(
      :adapter => 'mysql',
      :host => '...',
      :username => '...',
      :password => '...',
      :database => 'alternatedb'
      )

    end
end

, , ( ...). , , . , ?

, Heroku -, apache/rails.

, dbcharmer magicmodels, , , . !

+3
1

:

( ...).

, , , , , . , , , .

, ActiveRecord , , .

:

class MyAppModel < ActiveRecord::Base
  self.abstract_class = true
end

, , :

class User < MyAppModel
  #stuff
end

, , ActiveRecord.

, ApplicationController create_connection MyAppModel .

, . , . .

+4

Source: https://habr.com/ru/post/1738379/


All Articles