Rails returns the results of other queries when connecting to multiple databases.

On a server with nginx and a unicorn, I have rails configured to connect to two different databases. With a small load, web requests to the endpoints that access the second rail database return the results of other requests.

For example, if there are simultaneous calls to http://example.com/user/111/address and http://example.com/user/222/address , sometimes the address for user 222 will be returned for BOTH calls, and sometimes it will return address for user 111 when accessing BOTH.

Entity for an address is very simple.

 class UserController < ApplicationController before_filter :load_user def address address = @user.address render json: address, status: 200 end private def load_user @user = User.find params[:id] end end 

The User and Address models have access to the second database and inherit from the base class that connects to this database:

 class OtherDbActiveRecord < ActiveRecord::Base self.abstract_class = true establish_connection "#{Rails.env}_other_db" # Prevent creation of new records and modification to existing records def readonly? return true end # Prevent objects from being destroyed def before_destroy raise ActiveRecord::ReadOnlyRecord end end class User < OtherDbActiveRecord has_one :address end class Address < OtherDbActiveRecord belongs_to :user end 

Is there a way to connect to the second db that I am missing? What can cause ActiveRecord to return results for another query?

+4
source share
1 answer

OtherDbActiveRecord is the only object. Each ruby ​​class is an object, and it is the only object. When you call connection_connection, it sets the state of this (one) object for this connection.

Try to duplicate classes with different class names.

 class User < ActiveRecord::Base end class UserOther < OtherDbActiveRecord end class Address < ActiveRecord::Base end class Address Other < OtherDbActiveRecord end 
0
source

Source: https://habr.com/ru/post/1434719/


All Articles