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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With