has_manyを使用した複数のデータベース接続
-
25-10-2019 - |
質問
複数のデータベース接続を使用して作業を通じて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を場所に追加して、このような場所のデフォルトデータベースを上書きしようとしました。
#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"
所属していません StackOverflow