4

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!

H Mihail
  • 613
  • 8
  • 18
  • http://stackoverflow.com/questions/17311199/connecting-to-multiple-databases-in-ruby-on-rails – Axel Tetzlaff Aug 19 '15 at 09:55
  • But that example uses a model. I don't want to use a model, since the remote database is very big, and I only need a few columns from 2 joined tables. – H Mihail Aug 19 '15 at 10:03
  • I don't see how the number of columns in a table or the size of the overall DB affects the decision of creating models? Creating models does not force you to load the whole DB and also not selecting all columns of a table – Axel Tetzlaff Aug 19 '15 at 10:11
  • The remote table is already created, and I only need to read some columns. I don't know how to create the model and define the fields, without migration. – H Mihail Aug 19 '15 at 10:15
  • check solution from this thread: http://stackoverflow.com/questions/15408285/rails-3-execute-custom-sql-query-without-a-model – greg Aug 19 '15 at 10:38

1 Answers1

8

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
Axel Tetzlaff
  • 1,355
  • 8
  • 11