例如,我有一个 study_history 模型:
rails g model study_history lesson:references user:references history_type:references
- 在 database.yml 中定义 mysql 部分
player_records:
adapter: mysql2
encoding: utf8
host: 1.2.3.4
username: root
password:
timeout: 5000
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 20 } %>
database: player_records
- 修改StudyHistory模型,添加建立连接,它会连接你上面的mysql数据库player_records(我先在mysql服务器中添加了这个数据库):
class StudyHistory < ApplicationRecord
establish_connection :player_records
belongs_to :lesson
belongs_to :user
belongs_to :history_type
end
- 使用迁移文件中的连接创建表:
class CreateStudyHistories < ActiveRecord::Migration[6.0]
def change
StudyHistory.connection.create_table :study_histories do |t|
t.references :lesson, null: false
t.references :user, null: false
t.references :history_type, null: false
t.timestamps
end
end
end
现在,你可以运行了
rails db:migrate
就是这样,我在 rails 6 中测试过,它的工作原理非常棒,您可以从不同的数据库组合(本地 sqlite3 和远程 mysql)获取数据。
irb(main):029:0> StudyHistory.first.lesson
(42.5ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_Z
ERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
StudyHistory Load (30.0ms) SELECT `study_histories`.* FROM `study_histories` ORDER BY `study_histories`.`id` ASC LIMIT 1
(0.0ms)
SELECT sqlite_version(*)
Lesson Load (0.1ms) SELECT "lessons".* FROM "lessons" WHERE "lessons"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<Lesson id: 1, title: "people", cn: nil, description: nil, version: nil, course_id: 1, created_at: "2020-03-01 23:57
:02", updated_at: "2020-05-08 09:57:40", level: "aa", ready: false, pictureurl: "/pictures/kiss^boy and girl^boy^girl.jp
g">