繁体   English   中英

当连接到多个数据库时,Rails返回其他请求的结果。

[英]Rails returning results from other requests when connecting to multiple databases.

在运行nginx和unicorn的服务器上,我将rails配置为连接到两个不同的数据库。 即使是轻负载,对访问第二个rails数据库的端点的Web请求也将返回其他请求的结果。

例如,如果同时调用http://example.com/user/111/addresshttp://example.com/user/222/address ,有时会为BOTH调用返回用户222的地址,有时它会在BOTH呼叫时返回用户111的地址。

地址的要点非常基础。

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 

模型UserAddress都访问第二个数据库并从连接到该数据库的基类继承:

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 

是否有一个步骤连接到我错过的第二个数据库? 什么可能导致ActiveRecord返回不同查询的结果?

OtherDbActiveRecord是单个对象。 每个ruby类都是一个对象,它是一个单独的对象。 当您调用establish_connection时,它会将该(一个)对象的状态设置为给定连接。

尝试使用具有不同类名的重复类。

class User < ActiveRecord::Base
end

class UserOther < OtherDbActiveRecord
end

class Address < ActiveRecord::Base
end

class Address Other < OtherDbActiveRecord
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM