I've faced a trouble while implementing multiple database connections in a Rails 4 application. Along with the primary database connection I've created secondary connection by specifying details in database.yml
.
secondary_base:
adapter: postgresql
encoding: unicode
host: localhost
database: secondary_db
pool: 5
username: postgres
password: postgres
Then created a model named SecondaryBase
which holds the connection to that secondary database. Code given below:
secondary_base.rb
class SecondaryBase < ActiveRecord::Base
self.abstract_class = true
establish_connection "secondary_base"
end
Then added two models Member
and Subdomain
.
member.rb
class Member < SecondaryBase
has_and_belongs_to_many :subdomains
end
subdomain.rb
class Subdomain < SecondaryBase
has_and_belongs_to_many :members
end
Now as you can see that Member
and Subdomain
models are related by has_and_belongs_to_many
relationship. So when I'm trying to insert data to the join table named members_subdomains
, It's now working and giving me the error something like that PG: Undefined table
, though the table exits in secondary_db
database. What I understood that rails is trying to find the members_subdomains
table in primary database.But when I tried the same code in Rails 3.2.13, then there were no problem at all, everything is fine. Have any of you deal with a similar problem before? Please help.