繁体   English   中英

我可以让DataMapper和ActiveRecord在Rails应用程序中使用不同的数据库适配器吗?

[英]Can I have DataMapper and ActiveRecord use different database adapters in a Rails app?

我有一个一直在使用DataMapper的Rails应用程序。 我即将将其转换为使用ActiveRecord。 如果可能的话,我想一次做一个模型(或一组模型)。

现在,我什至无法启动应用程序,因为两个ORM似乎需要不同的适配器。

如果database.yml指定适配器mysql ,则bundler/rubygems_integration.rb会引发:

Please install the mysql adapter: `gem install activerecord-mysql-adapter` (mysql is not part of the bundle. Add it to Gemfile.)

如果指定mysql2 ,则activesupport/dependencies会引发:

cannot load such file -- dm-mysql2-adapter (LoadError)

我试图创建ActiveRecord的一个单独的环境与mysql2适配器,然后使用establish_connection从个别型号我想先转换,但应用程序仍无法启动。

有人成功做到了吗?

解决此特定问题的方法似乎是为DataMapper提供其数据库连接信息作为uri选项,而ActiveRecord将使用适配器,用户名,根目录和主机选项指定的连接。

defaults: &defaults
  adapter: mysql2
  username: root
  password: somePassword
  host: localhost

development: &development
  database: myapp_dev
  uri: mysql://localhost/myapp_dev?user=root&password=somePassword
  <<: *defaults

test:
  database: myapp_test
  uri: mysql://localhost/myapp_test?user=root&password=somePassword
  <<: *defaults
production:
  database: myapp_dev
  <<: *defaults

但是,要使两个ORM很好地协同工作将涉及许多其他问题。 我个人已经放弃了,只是立即删除DataMapper。

你可以试试看 加载ActiveRecord模型后,需要运行此代码。

db_settings = YAML::load_file("#{ROOT_PATH}/config/database_settings_for_active_record.yml")
db_config = db_settings[Rails.env]
spec = Hash.new
[:adapter, :host, :username, :password, :pool, :database].each { |x| spec.merge!(x => db_config[x.to_s]) }
YourModel.establish_connection(spec)

database_settings_for_active_record.yml将包含以下内容:

production:
  adapter: mysql2
  encoding: utf8
  host: localhost
  username: root
  password:
  pool: 5
  database: my_db

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM