Mehrere Datenbankverbindungen mit Has_Many durch
-
25-10-2019 - |
Frage
Wie kann ich durch die Arbeit mit mehreren Datenbankverbindungen ein Has_Many herstellen?
Ich habe eine Datenbank mit dem Namen "Master", die die Standortinformationen enthält. Das wird aus einer separaten Anwendung aktualisiert. Benutzer können Zugriff auf viele Standorte haben, aber alle anderen Modelle befinden sich in einer anderen Datenbank mit dem Namen "Budget". So sind die Modelle eingerichtet.
# 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
Wenn ich Befehle über IRB ausführe, bekomme ich die folgenden
> 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
Ich habe versucht, die aktuelle Rails -Env hinzuzufügen, um zu versuchen, die Standarddatenbank für den Ort zu überschreiben, wie folgt: # place.rb class Place <ActivereCord :: Basis deta. connection Rails.env gehört
#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
Das half nicht. Irgendwelche Ideen?
Lösung
Ein Freund antwortete dies für mich, und ich dachte, es könnte für andere von Nutzen sein.
class Location < ActiveRecord::Base
#establish_connection "master"
def self.table_name() "master.locations" end
has_many :places
has_many :users, :through => :places
end
Andere Tipps
Die Antwort funktioniert für mich, aber ich verwende diese Version in meiner Beziehungstabelle:
self.table_name = "master.locations"