I need to get / update / delete data in the external database, not related to the database of the application itself. It is necessary to refer to it from the code. Tell me where it is to arrange, connection initialization, CRUD operations. I guess in the model. Maybe there is some example of how best to write this?

  • Where do the base details come from and when? What is the expected number of them? How do you want to maintain connections? Is that only MySQL DBMS expected at that end? - D-side
  • @ D-side, base is one, only mysql, I can specify base details when raising a connection, I do not need to support connections, it is necessary that CRUD operations are performed by necessity - S.Ivanov
  • Then it looks like this database just needs to be registered in database.yml , no? If she is only one. UPD: or even make a FEDERATED table directly in the application database. - D-side
  • @ D-side, so in database.yml same data of the database with which the application works is indicated. They are already there, but I need another base, which I need to access from the code by opening the connection. The application itself has nothing to do with this base - S.Ivanov

1 answer 1

There are several possible solutions.

At the level of ActiveRecord

You can invent a key under which the details of the remote database will be stored, for example, external , and enter them into database.yml :

 external: adapter: mysql host: example.com ... 

... and in the model specify ActiveRecord to apply to that database:

 class Model < ActiveRecord::Base establish_connection :external end 

... and you can specify the details directly in the arguments for establish_connection hashmap, but it is better to store them in the configuration file of your choice. database.yml , if you don't commit it, is a good choice. And anyway, here is the documentation to establish_connection .

MySQL level

MySQL has a FEDERATED storage engine that delegates data storage to another MySQL server. First, you need to enable this engine at the database server level, and then create a reflection table directly in the application database .

Rails won't even need to know that the data is actually somewhere far away.