In Rails, how do I execute direct SQL code in another database?

Like this.

I am writing a Rails application that will monitor the quality of data for some specific databases. To do this, I need to be able to perform direct SQL queries on these databases, which, of course, does not coincide with the one used to manage Rails application models. In short, this means that I cannot use the trick going through the base ActiveRecord connection.

The databases to which I must connect are not known at design time (that is: I cannot put their data in database.yaml). Rather, I have a "database_details" model that the user will use to enter information about the databases over which the application will execute queries at run time.
Thus, the connection to these databases is really dynamic, and details are only allowed at runtime.

How can i do this?

Thanks
Rollo

+3
source share
3 answers

I had a situation where I had to connect to hundreds of different instances of an external application, and I made code similar to the following:

  def get_custom_connection(identifier, host, port, dbname, dbuser, password)
      eval("Custom_#{identifier} = Class::new(ActiveRecord::Base)")
      eval("Custom_#{identifier}.establish_connection(:adapter=>'mysql', :host=>'#{host}', :port=>#{port}, :database=>'#{dbname}', " +
      ":username=>'#{dbuser}', :password=>'#{password}')")  
    return eval("Custom_#{identifier}.connection")
  end

: ActiveRecord:: Base, , SQL , .

+6

, ,

ActiveRecord::Base.establish_connection(
   :adapter  => "mysql",
   :host     => "localhost",
   :username => "myuser",
   :password => "mypass",
   :database => "somedatabase"
)

, somedatabase database_model.database_name. adatpter

ActiveRecord:: Base.establish_connection documentation

ActiveRecord::Base.find_by_sql("select * ") 

sql.

ActiveRecord:: Base.find_by_sql

Mr Matt ,

(, ) , :)

+9

You can do it through self.establish_connection

0
source

Source: https://habr.com/ru/post/1697031/


All Articles