7

複数のデータベース接続を使用してhas_manyを作成するにはどうすればよいですか?複数のデータベース接続とhas_manyから

私は、位置情報を保持する "master"という名前のデータベースを持っています。それは別のアプリケーションから更新されます。ユーザーは多くの場所にアクセスできますが、他のすべてのモデルは「予算」という名前の別のデータベースにあります。モデルの設定方法は次のとおりです。

# 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てコマンドを実行すると、私はこのように、場所のデフォルトのデータベースを試してみて、上書きするの場所に現在のレールのenvを追加しようとした以下の

> 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 

取得: #場所を.RB クラスプレイス<のActiveRecord ::ベース establish_connection Rails.env belongs_toの:ユーザー belongs_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 

それは役に立たなかった。何か案は?

+1

また、あなたは、データベースを定義し、あなたのconfig/database.ymlをファイルから抜粋 – Tilo

+0

Iを投稿する必要があります更新しました。ありがとうございました。私のケースでは –

答えて

3

友人が私のためにこれに答えて、私はそれが他の人に何らかの役に立つかもしれないと考えました。

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

、データベースは外部サーバーにあり、このソリューションは動作しません.. –

1

答えは私のために動作しますが、私は私の関係テーブルでこのバージョンを使用します。

self.table_name = "master.locations" 
関連する問題