문제

There are many questions and answers regarding the creation of multiple connections to multiple databases in rails:

https://stackoverflow.com/a/7480330/2120023

https://stackoverflow.com/a/6305540/2120023

Example from outside stackoverflow: http://ilikestuffblog.com/2012/09/21/establishing-a-connection-to-a-non-default-database-in-rails-3-2-2/

But I have yet to find a solution that works when using a model that appears in both databases.

If my default db has a table titles and my Other db has a table titles how do I access the other database's Title model?

title.rb:

class Title < ActiveRecord::Base
end

othertitle.rb:

class Other < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "other_#{Rails.env}"
end

class OtherTitle < Other
end

I can't use the above because I get this error (EDIT: for clarity there is no other_titles table in either db only a titles table -> EDIT 2: If I do create an other_titles table in the Other database, everything works perfectly but that does not help me access the titles table.):

ActiveRecord::StatementInvalid: Mysql2::Error: Table 'other.other_titles' doesn't exist: SHOW FULL FIELDS FROM `other_titles`

I also can't use class Title < Other because I get a TypeError: superclass mismatch for class Title error.

database.yml

development:
  adapter: mysql2
  encoding: utf8
  database: db_dev
  pool: 5
  username: xxxx
  password: xxxx
  socket: /var/lib/mysql/mysql.sock

production:
  adapter: mysql2
  encoding: utf8
  database: db
  pool: 5
  username: xxxx
  password: xxxx
  socket: /var/lib/mysql/mysql.sock


other_development:
  adapter: mysql2
  encoding: utf8
  database: other_dev
  pool: 5
  username: xxxx
  password: xxxx
  socket: /var/lib/mysql/mysql.sock

other_production:
  adapter: mysql2
  encoding: utf8
  database: other
  pool: 5
  username: xxxx
  password: xxxx
  socket: /var/lib/mysql/mysql.sock 
도움이 되었습니까?

해결책

I found the answer and it is quite simple:

class OtherTitle < Other
  self.table_name='titles'
end

Referenced here:

Efficient way to pull data from second database?

and here:

Cannot connect to two postgres databases in rails 3.2.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top