We have a primary database where all of our app resides.
But there's a second database (updated from an external source), that I'd like to be able to connect to so I can pull data from it. I don't need to write anything...just read.
It also only has one table that I'm pulling from.
I really just need to do something like:
OtherDatabase.articles.where(id > 1000)
And that's it.
So how can I do this in Rails (running 3.2.13)?
Copy/Paste:
For a single-master situation, you could define another database connection in database.yml for the read slave:
This database is backed by a module, which mirrors the ActiveRecord classes using this database connection:
Now, all pre-existing models can be accessed through the read_slave connection by prefixing the model class with ReadSlave::.
For simple scenarios, Rails can support this without any extra gems; simply define the database in database.yml:
Then in the model you want to use the other database add:
And then you can perform your query:
=)
Firstly, we need to define the external database:
For something like this, I prefer using a module that takes care of database connections.
By passing a block to a module like this we can make sure we don't bleed our queries into a database where they don't belong or forget to revert our connection. Also, we default to ActiveRecord::Base so that we can work with any of our models. However, if we know we're only using one and want to isolate our model usage, we can pass it as the secondary parameter.
The resulting implementation can look something like this:
Now we have a nice and clean block we can use anywhere we like, use any models we want inside the block and always be operating on the extneral database. Once that block is finished, we know we're working back on our original database.