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!

5
  • stackoverflow.com/questions/17311199/… Commented Aug 19, 2015 at 9: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. Commented Aug 19, 2015 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 Commented Aug 19, 2015 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. Commented Aug 19, 2015 at 10:15
  • check solution from this thread: stackoverflow.com/questions/15408285/… Commented Aug 19, 2015 at 10:38

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

1 Comment

In case anyone is still using this answer in 2024, it only worked for me when I provided the new db key name as a symbol establish_connection :other_db. Might be a local issue, but it really didn't like a string value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.