【发布时间】:2014-09-26 20:33:52
【问题描述】:
我有一个 JRuby 应用程序,我正在尝试为两个完全不同的服务器上的数据库创建 has_many through: 关系。我知道连接不会跨不同服务器上的表工作。我想要的是模拟连接,这样使用该模型的开发人员就不必(因为)知道跨服务器连接。
此设置还有一些额外的复杂性:
- 远程数据库是只读的
- 远程数据库中的表名和主键不遵循 Rails 命名约定。 (远程数据库是Data Warehouse)
- 我希望能够像使用
has_and_belongs_to_many一样使用模型。
我考虑过编写自己的自定义 association,但这有点复杂,除了阅读 Rails 代码之外,我找不到任何指南或任何起点。
有没有我想念的简单方法来做到这一点?
构建自定义 ActiveRecord 关联是最好的方法吗?如果是,我应该从哪里开始?
代码类似于我的设置:
config/database.yml
development:
adapter: postgresql
encoding: unicode
database: main
username: username
password: password
host: localhost
pool: 5
remote_development: # Read only
adapter: jdbcmssql
driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: 'jdbc:sqlserver://foo.com;databaseName=main'
username: username
password: password
app/models/account.rb
class Portfolio < ActiveRecord::Base
#has_and_belongs_to_many :dim_users, join_table: :accounts_dim_user
end
app/models/remote_model_base.rb
class RemoteModelBase
require "#{Rails.root}/lib/sqljdbc4.jar"
self.abstract_class = true
establish_connection "remote_#{Rails.env}".to_sym
after_initialize :readonly!
end
app/models/dim_user.rb
class DimUser < RemoteModelBase
self.table_name = 'DimUser'
self.primary_key = 'dwidDimUser'
#has_and_belongs_to_many :accounts, join_table: :accounts_dim_user
end
config/schema.rb
ActiveRecord::Schema.define(version: 20140925200106) do
create_table "accounts", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "accounts_dim_user", force: true, id: false do |t|
t.integer "dwidUser"
t.integer "account_id"
t.datetime "created_at"
t.datetime "updated_at"
end
# Defined in the remote database but it might look something like this
# create_table "DimUser" do |t|
# t.integer dwidUser
# # ...
# end
【问题讨论】:
-
我找到了 gem st-elsewhere,但我担心它已经 5 岁了。
标签: ruby-on-rails-4 jruby data-warehouse mssql-jdbc