Mongo有许多关系生成错误的mongoid查询

时间:2017-08-28 22:02:08

标签: ruby-on-rails mongodb mongoid ruby-on-rails-5

我和顾客之间有一对多的关系。我的客户类别是:

class Customer
  include Mongoid::Document

  has_many :purchases
end

这是我的购买课程:

class Purchase
  include Mongoid::Document

  belongs_to :customer, class_name: "Customer", foreign_key: :customer_id
end

我想我已经正确设置了密钥。不确定是否注意到客户和购买都会被外部进程填充,这些进程会为mongodb提供种子。

但这是关于错误生成的查询的部分,示例1(来自rails控制台):

Customer.first.purchases

生成此查询:

{"find"=>"purchases", "filter"=>{"customer_id"=>BSON::ObjectId('59a48bc9be66bdb7de3108b5')}}

但正确的查询是:

{"find"=>"purchases", "filter"=>{"customer_id"=>1006}}

当我从关系的另一端接近这个时,同样的事情:

Purchase.first.customer

生成这个:

{"find"=>"customers", "filter"=>{"_id"=>10006}, "sort"=>{"_id"=>1}, "limit"=>1, "singleBatch"=>true}

但正确的查询是:

{"find"=>"customers", "filter"=>{"customer_id"=>10006}, "sort"=>{"_id"=>1}, "limit"=>1, "singleBatch"=>true}

我在这里做错了什么?

问题更新:

当我尝试手动操作数据时,再次尝试使用rails console:

purchase = Purchase.last
purchase.customer_id = 10006
purhcase.save!

产生这个:

Mongoid::Errors::Validations: 
message:
  Validation of Purchase failed.
summary:
  The following errors were found: Customer can't be blank
resolution:
  Try persisting the document with valid data or remove the validations.

但我实际上可以继续找到这条记录:

Customer.where(customer_id: 10006).any?
D, [2017-08-28T18:04:32.053474 #86323] DEBUG -- : MONGODB | localhost:27017 | api_be_development.find | STARTED | {"find"=>"customers", "filter"=>{"customer_id"=>10006}}
D, [2017-08-28T18:04:32.054697 #86323] DEBUG -- : MONGODB | localhost:27017 | api_be_development.find | SUCCEEDED | 0.0009580000000000001s
=> true

0 个答案:

没有答案