如何通过使用多个数据库连接来制作has_many?

我有一个名为“主”的数据库,该数据库包含位置信息。从一个单独的应用程序更新。用户可以访问许多位置,但是所有其他模型都位于另一个名为“预算”的数据库中。这是设置模型的方式。

# place.rb
class Place < ActiveRecord::Base
  belongs_to :user
  belongs_to :location
end

# user.rb
class User < ActiveRecord::Base
  has_many :locations, :through => :places
  has_many :places
end

# location.rb
class Location < ActiveRecord::Base
  establish_connection "master"
  has_many :places
  has_many :users, :through => :places
end

当我通过IRB运行命令时,我会得到以下内容

> Location.first.places.create(:user_id => 1)
> #<Place id: 1, user_id: 1, location_id: 1, created_at: "2011-11-28 20:58:43",  updated_at: "2011-11-28 20:58:43">

> Location.first.places
> [#<Place id: 1, user_id: 1, location_id: 1, created_at: "2011-11-28 20:58:43", updated_at: "2011-11-28 20:58:43">]

> Location.first.users
> [#<User id: 1, username: "toby", role: "guest", created_at: "2011-11-28 17:45:40", updated_at: "2011-11-28 17:45:40">

> User.first.locations
> Mysql2::Error: Table 'master.places' doesn't exist: SELECT `locations`.* FROM `locations` INNER JOIN `places` ON `locations`.`id` = `places`.`location_id` WHERE `places`.`user_id` = 1 ActiveRecord::StatementInvalid: Mysql2::Error: Table 'master.places' doesn't exist: SELECT `locations`.* FROM `locations` INNER JOIN `places` ON `locations`.`id` = `places`.`location_id` WHERE `places`.`user_id` = 1

我尝试添加当前的Rails Env以尝试尝试并覆盖位置的默认数据库,例如:#place.rb class place <activerecord :: base stable_connection rails.env anders_to anders_to:user allat anders_to:位置端

#database.yml

master:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: master
  pool: 5
  username: root
  password:
  socket: /var/run/mysqld/mysqld.sock
development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: budget_development
  pool: 5
  username: root
  password:
  socket: /var/run/mysqld/mysqld.sock

那无济于事。有任何想法吗?

有帮助吗?

解决方案

一个朋友为我回答了这一点,我认为这可能对其他人有用。

class Location < ActiveRecord::Base
  #establish_connection "master"
  def self.table_name() "master.locations" end
  has_many :places
  has_many :users, :through => :places
end

其他提示

答案对我有用,但是我在关系表中使用此版本:

self.table_name = "master.locations"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top