简体   繁体   中英

Using Rails, can I retrieve data from a legacy database without using ActiveRecord?

I have a new version of a website that needs to pull some information from the legacy version of a website. The old and new databases have the same tables, fields, etc. The old website is running Rails 3. The new website is running Rails 5.

I want to pull some records (let's call them Orders) from the old database into the new database.

My first attempt was to create a model class and establish a connection using ActiveRecord like so:

class OldOrder < ActiveRecord::Base
  establish_connection(
    adapter:  "mysql2",
    host:     "old_server",
    username: "user",
    password: "password",
    database: "database"
  )
end

and then call upon the records like so:

OldOrder.where(order_number: "whatever").each do |order|
  # and so on
end

and so on.

Unfortunately, whenever I run any command on OldOrder, I receive the following error message:

*** RuntimeError Exception: Your version of MySQL (5.0.77) is too old. Active Record supports MySQL >= 5.1.10.

So I figured I have two options: upgrade the mysql on the old server (which would be undesirable due to the nature of the legacy server), or get the data some other way.

Searching StackOverflow for potential answers, I tried using raw sql:

 sql = "Select * from ... your sql query here"
 records_array = ActiveRecord::Base.connection.execute(sql)

But since it uses ActiveRecord::Base to run the sql, it also failed.

Is there any way to connect to this old database within Rails without using ActiveRecord, or should I be looking for alternatives?

Thank you for your time!

Following Dave Slutzkin's comment, I installed the sequel gem and connected to the old database in much the same way:

DB = Sequel.connect(
  adapter: :mysql2,
  host: 'old_server',
  user: 'user',
  password: 'password',
  database: 'database'
)

I can then call statements on this DB object in much the same way that ActiveRecord can, following sequel's documentation.

old_orders = DB[:orders]
old_orders.where(whatever: "whatever").each do |old_order|
   # Create new order
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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