If you are coming from a previous version of Rails, you may be wondering why the update action of a RESTful route is mapped to the HTTP verb PATCH instead of PUT. In the HTTP standards document RFC 57892, it outlines that a PUT request to a given resource is meant to completely replace it on the origin server. However, when updating a resource in Rails, rarely, if ever, do you replace an entire resource when performing an update. For example, when updating an Active Record model, Rails sets the attribute updated_at timestamp, not the requesting client.

To follow better HTTP semantics, Rails will be using the HTTP verb PATCH for updates. PATCH allows for both full and partial updates of a resource, and is more suited to how Rails updates resources.If you are upgrading an existing Rails application, the HTTP verb PUT will still map to the update action in
RESTful routes, but it’s recommended to use PATCH moving forward.

Connect to Multiple Databases In Rails

The simple default Rails convention of connecting to one database per appli-cation is suitable most of the time. That’s why its creators made it so easy.But what if you need to step outside the norm and connect to multiple databases? What if, for example, you need to connect to a commercial appli- cation’s tables to integrate your nifty new rich web application with a legacy tool that your company has relied on for years? How do you configure and create those multiple connections? How do you cleanly connect to multiple databases in a single Rails application?
To connect to multiple databases in a Rails application, we’ll set up named
connections in our application’s database configuration, configure our Active
Record models to use it, and use inheritance to safely allow multiple models
to use the new named connection.
To understand how to connect to multiple databases from your Rails applica-
tion, the best place to start is to understand how the default connections are
made. How does an application go from a YAML configuration file to a database
connection? How does an Active Record model know which database to use?
When a Rails application boots, it invokes the Rails initialization process. The
initialization process has the big job of ensuring that all the components of
Rails are properly set up and glued together. In Rails 3 and newer, this process
does its work by delegating to each subframework of Rails and asking that
subframework to initialize itself. Each of these initializers is called a Railtie .
Active Record defines ActiveRecord::Railtie to play the initialization role. One of
its jobs is to initialize database connections.
The Active Record Railtie is responsible for calling the method ActiveRe-
cord::Base.establish_connection() . If you call this method with no arguments, it will
check the value of the Rails.env variable and will look up that value in the
loaded config/database.yml . The default value for Rails.env is development . So, by

By default, on initialization a Rails application discovers which environment it’s
running under (development, test, or production in a stock Rails app) and finds a
database configuration in config/database.yml that is named for the current environment.
Here’s a simple sample:
adapter: mysql2
encoding: utf8
reconnect: false
database: multiple_dbs_development
pool: 5
username: root
socket: /tmp/mysql.sock
adapter: mysql2
encoding: utf8
reconnect: false
database: multiple_dbs_test
pool: 5
username: root
socket: /tmp/mysql.sock
adapter: mysql2
encoding: utf8
reconnect: false
database: multiple_dbs_production
pool: 5
username: root
socket: /tmp/mysql.sock
If you’ve done any database work with Rails, you’ve already seen (and probably con-
figured) a file that looks like this. The naming conventions make it quite obvious what
goes where, so you may find yourself blindly editing this file to achieve the desired
default, if you start a Rails application, it looks up the database configuration
section named development in its config/database.yml file and sets up a connection
to that database.
Note that an actual connection has not yet been established. Active Record
doesn’t actually make the connection until it needs it, which happens on the
first reference to the class’s connection() method. So if you’re following along
and watching open database connections, don’t be surprised if you don’t see
an actual connection made immediately after your application boots.

Having set up a connection to a database solves only part of the puzzle. That
connection still has to be referenced by the model classes that need it. Things
get interesting here. When the default connections are made by the Railtie ,
they are made directly from the ActiveRecord::Base class, which is the superclass
of all Active Record models. Because the call to establish_connection() is made on
ActiveRecord::Base , the connection is associated with the ActiveRecord::Base class
and is made available to all of its child classes (your application-specific
So, in the default case, all your models get access to this default connection.
If you make a connection from one of your model classes (by calling establish_con-
nection() ), that connection is available from that class and any of its children
but not from its superclasses, including ActiveRecord::Base .
When asked for its connection, the behavior of a model is to start with the
exact class the request is made from and work its way up the inheritance
hierarchy until it finds a connection. This is a key point in working with
multiple databases. A model’s connection applies to that model and any of
its children in the hierarchy unless overridden.
Now that we know how Active Record connections work, let’s put our knowl-
edge into action. We’ll contrive a couple of example databases with which to
demonstrate our solution. The following is our config/database.yml file. We have
two databases. One is labeled as development and will be our default database.
The other is labeled products and simulates the hypothetical scenario of having
an existing, external product database for a new application.
adapter: mysql2
encoding: utf8
reconnect: false
database: myrailsdatabase_development
pool: 5
username: root
socket: /tmp/mysql.sock
adapter: mysql2
encoding: utf8
reconnect: false
database: products
pool: 5
username: root
socket: /tmp/mysql.sock

We’ll also create some tables in these databases so we can hook them up to
Active Record models. For our default Rails database, we’ll create a migration
defining tables for users and shopping carts.
class AddUsersAndCarts < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.string :email
create_table :carts do |t|
t.integer :user_id
create_table :selections do |t|
t.integer :cart_id
t.integer :product_id
In a typical scenario like this, the second database would be one that already
exists, which you wouldn’t want to (or be able to) control via Active Record
migrations. As a result, Active Record’s migrations feature wasn’t designed
to manage multiple databases. That’s OK. If you have that level of control
over your databases and the tables are all related, you’re better off putting
them all together anyway. For this example, we’ll assume that the products
database already has a table called products , with a varchar field for the product
name and a float for the price. For those following along, the following simple
DDL can be used to create this table on a MySQL database:
CREATE TABLE `products` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`price` float default NULL,
Now that we have our databases set up, we’ll generate models for User , Cart ,
and Product . The User model can have an associated Cart , which can have mul-
tiple Product s in it. The User class is standard Active Record fare:
class User < ActiveRecord::Base
has_one :cart

Things start to get a little tricky with the Cart class. It associates with User in
the usual way. We’d like to use has_many() with a join model to link to :products ,
but we can’t, because our products table is not in the same database. The
has_many() method will result in a table join, which we can’t do across database
connections. Here’s the Cart class without any association with the Product
class Cart < ActiveRecord::Base
Before we deal with hooking Cart s to Product s, let’s look at our Product model:
class Product < ActiveRecord::Base
establish_connection :products
As we learned earlier, Active Record establishes connections in a hierarchical
fashion. When attempting to make a database connection, Active Record
models look for the connection associated with either themselves or the
nearest superclass. So, in the case of the Product class, we’ve set the connection
directly in that class, meaning that when we do database operations with the
Product model, they will use the connection to our configured products database.
If we were to load the Rails console now, we could see that we are indeed
connecting to different databases depending on the model we’re referencing:

>> $ rails console
>> Cart.connection.current_database
=> “myrailsdatabase_development”
>> Product.connection.current_database
Great! Now if we were to call, say, Product.find() , we would be performing our
select against the products database. So, how do we associate a Cart with Product s?
We have many different ways to go about doing this, but I tend to favor the
laziest solution. To make the connection, we’ll create a mapping table in our
application’s default database (the same one the cart table exists in):
class CreateProductReferences < ActiveRecord::Migration
def self.up
create_table :product_references do |t|
t.integer :product_id
def self.down

drop_table :product_references
This table’s sole purpose is to provide a local reference to a product. The
product’s id will be stored in the product reference’s product_id field. We then
create a model for this new table:
class ProductReference < ActiveRecord::Base
belongs_to :product
has_many :selections
has_many :carts, :through => :selections
def name
def price
We’ve created the has_many() relationship between our new ProductReference class
and the Cart class with a join model called Selection , and we’ve associated each
ProductReference with a Product . Here’s the Selection definition:
class Selection < ActiveRecord::Base
belongs_to :cart
belongs_to :product, :class_name => “ProductReference”
Since our Product class is simple, we have also manually delegated calls to
name() and price() to the Product , so for read-only purposes, the product reference
is functionally equivalent to a Product .
All that’s left is to associate the Cart with its products:
class Cart < ActiveRecord::Base
has_many :selections
has_many :products,
:through => :selections
We can now say things such as and get the data
we desire. This solution would, of course, require the necessary rows to be
created in the product_references table to match any products we have in the
alternate database. This could be done either in a batch or automatically at

Now what if you would like to connect to multiple tables in the same external
database? Based on what we’ve done so far, you’d think you could add calls
to establish_connection() in the matching models for each of the new tables. But,
what you might not expect is that this will result in a separate connection for
every model that references your external database. Given a few tables and
a production deployment that load balances across several Rails processes,
this can add up pretty quickly.
Thinking back to what we learned about how database connections are
selected based on class hierarchy, the solution to this problem is to define a
parent class for all the tables that are housed on the same server and then
inherit from that parent class for those external models. For example, to ref-
erence a table called tax_conversions on the products database, we could create a
model called External as follows:
class External < ActiveRecord::Base
self.abstract_class = true
establish_connection :products
Then, our Product and TaxConversion models could inherit from External like so:
class Product < External
class TaxConversion < External
Note that we’ve moved the establish_connection() call from Product to External . All
subclasses of External will use the same connection. We also set abstract_class to
true to tell Active Record that the External class does not have an underlying
database table.

opposed to direct database access. For read-only feeds of data that need to
participate in complex joins, consider replic