Avishek
Avishek

Reputation: 134

Multiple database connection in rails 4

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.

Upvotes: 3

Views: 2200

Answers (1)

infused
infused

Reputation: 24337

I believe you will need to switch from has_and_belongs_to_many to has_many :through to get this to work. In order to do that, just create a model for the join table - I'll call it `MemberSubdomain'.

class SecondaryBase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "secondary_base"
end

class MemberSubdomain < SecondaryBase
  self.table_name = 'members_subdomains'
end

class Member < SecondaryBase
  has_many :member_subdomains
  has_many :subdomains, :through => :member_subdomains, :source => :subdomain
end

class Subdomain < SecondaryBase
  has_many :member_subdomains
  has_many :members, :through => :member_subdomains, :source => :member
end

Upvotes: 3

Related Questions