Ruby on rails 3 连接到两个数据库Mongoid

Ruby on rails 3 连接到两个数据库Mongoid,ruby-on-rails-3,mongoid,multiple-databases,mongoid3,querying,Ruby On Rails 3,Mongoid,Multiple Databases,Mongoid3,Querying,我有两个数据库,我必须在我的应用程序中使用。我的mongoid.yml中有以下内容: development: # Configure available database sessions. (required) sessions: # Defines the default session. (required) default: # Defines the name of the default database that Mongoid can con

我有两个数据库,我必须在我的应用程序中使用。我的mongoid.yml中有以下内容:

development:
  # Configure available database sessions. (required)
  sessions:
    # Defines the default session. (required)
    default:
      # Defines the name of the default database that Mongoid can connect to.
      # (required).
      database: db_development
      username: myusername
      password: mypassword
      # Provides the hosts the default session can connect to. Must be an array
      # of host:port pairs. (required)
      hosts:
        - myserverip:27017
      databases:
        secondary:
          database: db2_development
          username: myusername
          password: mypassword
          # Provides the hosts the default session can connect to. Must be an array
          # of host:port pairs. (required)
          hosts:
           - myserverip:27018          
在我的模型文件中:

class MyModel
   include Mongoid::Document
   store_in database: "secondary"
   field :name, type: String
   field :age, type: Integer
end
我的模型中有数据。当我尝试查询时,出现以下错误:

Moped::Errors::QueryFailure (The operation: #<Moped::Protocol::Query
  @length=96
  @request_id=5
  @response_to=0
  @op_code=2004
  @flags=[:slave_ok]
  @full_collection_name="secondary.mymodel"
  @skip=0
  @limit=0
  @selector={"name"=>"Tom"}
  @fields=nil>
  failed with error 10057: "unauthorized db:secondary ns:secondary.mymodel lock type:0 client:10.100.55.40"
Moped::Errors::QueryFailure(操作:#“Tom”}
@字段=零>
失败,错误为10057:“未经授权的数据库:次要ns:secondary.mymodel锁类型:0客户端:10.100.55.40”

我尝试在线搜索,但无法获得任何解决方案。如有任何帮助,将不胜感激。提前感谢。

嗯,你能做到这一点吗?看起来你把yaml文件弄乱了

development:
  sessions:
    default:
      database: db_development
      username: my_username
      password: my_password
      hosts:
        - myserverip:27017
      options:
        consistency: :eventual
    writeable:
      database: db2_development
      username: myusername2
      password  mypassword2
      hosts:
        -  myserverip2:27018
      options:
        consistency: strong
在你的模型中写下这个

store\u在会话中:“可写”

仅供参考,我从未使用
密码
选项进行过测试,但我想它会起作用


希望此帮助

为了临时访问数据库(例如在脚本中),您可以使用MongoDB Ruby驱动程序:--

有关快速概述:

连接到数据库:

client=Mongo::client.new(['127.0.0.1:27017',:database=>'my_db')

db=client.database

通过mongoDB查询语法查询条目:


db['collection\u name'].find('field\u name'=>'field\u value')

谢谢你的回答,我添加了'localhost:27017'而不是'myserverip:27017'和'store\u in database:'db2\u name',而不是'store in session:'writeable',这对我来说很有用
class MyModel
   include Mongoid::Document
   store_in session: "writeable"
   field :name, type: String
   field :age, type: Integer
end