Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails connect to remote database without model

What is the best way to connect to a remote database from Rails just to pull some data? I need to execute a query on the remote server and retrieve the column values. These columns will be the stored locally within a model.

Thanks!

like image 491
H Mihail Avatar asked Mar 16 '23 01:03

H Mihail


1 Answers

For multiple database connection, you need to add the following codes to the database.yml file.

config/database.yml

other_db:
  adapter: mysql2
  database: db1_dev
  username: root
  password: xyz
  host: localhost

Then create a new model.

class ImportLine < ActiveRecord::Base
  establish_connection "other_db"
  self.table_name = "the_table_in_th_other_db"
end

Now you can select arbitrary columns like this:

ImportLine.select(:col1, :col2).find_each do |line| 
   puts "#{line.col1} -#{line.col1}"
end
like image 147
Axel Tetzlaff Avatar answered Mar 23 '23 04:03

Axel Tetzlaff