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?
1 answer
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.
database.yml, no? If she is only one. UPD: or even make aFEDERATEDtable directly in the application database. - D-sidedatabase.ymlsame 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