通过has_many进行多个数据库连接

问题描述 投票:0回答:3

如何通过多个数据库连接创建 has_many ?

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

# 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 中,以尝试覆盖 place 的默认数据库,如下所示: # 地点.rb 上课地点 < ActiveRecord::Base establish_connection Rails.env belongs_to :user belongs_to :location end

#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

那没有帮助。有什么想法吗?

ruby-on-rails activerecord ruby-on-rails-3.1 has-many-through
3个回答
4
投票

一位朋友帮我回答了这个问题,我想这可能对其他人有用。

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

2
投票

答案对我有用,但我在我的关系表中使用这个版本:

self.table_name = "master.locations"

0
投票

任何几年后阅读本文的人,请注意 Rails 7 已为

disable_joins: true
has_one
引入了显式
has_many
选项。

参考:https://edgeguides.rubyonrails.org/active_record_multiple_databases.html#handling-associations-with-joins-across-databases

© www.soinside.com 2019 - 2024. All rights reserved.