Rails - 向标准app db查询不同的mysql db

时间:2018-05-14 13:09:52

标签: mysql ruby-on-rails ruby ruby-1.8

我使用Rails 2.2.2和Ruby 1.8.6与遗留应用程序一起使用MySQL。 (请不要告诉我需要升级ruby / rails)。

我将我们的实时数据库备份安装为本地MySql中的不同数据库。这有时对查询历史数据很有用,因为它并不总是保留在我们的活动数据库中。

我希望能够做的就是这样的事情

➜ ansible-playbook -i hosts.yml playbook.yml

PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [This command will run.] **************************************************
ok: [localhost] =>
  msg: The group `existent_1` exists!

TASK [This command will not run.] **********************************************
skipping: [localhost]

TASK [This command will run.] **************************************************
ok: [localhost] =>
  msg: The group `existent_2` exists and this host is in it!

TASK [This command will not run.] **********************************************
skipping: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0

有谁知道如何做school_ids = [123, 456, 789] signin_counts = {} #collect current data school_ids.each do |school_id| signin_counts[school_id] ||= {} signin_counts[school_id][:now] = ActiveRecord::Base.connection.select_value("select count(*) from sign_ins where school_id = #{school.id}").to_i end #switch to the old database - how to do this? CURRENT_DB = "my_old_backup_db_name" school_ids.each do |school_id| signin_counts[school_id] ||= {} signin_counts[school_id][:then] = ActiveRecord::Base.connection.select_value("select count(*) from sign_ins where school_id = #{school.id}").to_i end #switch back CURRENT_DB = "my_regular_db_name" 部分?感谢

2 个答案:

答案 0 :(得分:1)

如果你在继承ActiveRecord::Base的模型文件中,你可以这样做:

  mysql_database = establish_connection (
    adapter: "mysql",
    host: "your_db_host",
    username: "your_db_username",
    password: "your_db_password",
    database: "your_db_name"
  )

这篇文章对如何使用establish_connection http://ilikestuffblog.com/2012/09/21/establishing-a-connection-to-a-non-default-database-in-rails-3-2-2/进行了很好的解释,并且可能已经足够大,与您的Rails版本相关,但是版本2和版本3之间有很多变化

答案 1 :(得分:0)

感谢@ DaveGoldberg的评论,我提出了这两种方法来说明如何做到这一点。显然,有更清洁的方法来打包它,我只想展示一种简单的方法。

def use_old_db
  config = {
    :adapter => 'mysql',
    :host => 'localhost',
    :username => 'my_username',
    :password => 'my_password',
    :database => 'name_of_database'
  }
  ActiveRecord::Base.establish_connection(config)
end

def use_new_db
  ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
end