工作环境: Rails 4.1.4 mongoid 4.0.0
以下是我的模特:
class User
field :first_name, type: String, default: ""
field :last_name, type: String, default: ""
include Mongoid::Document
belongs_to :user_info, polymorphic: true
end
class Employee
include Mongoid::Document
belongs_to: :company
has_one :user, class_name: 'User', as: :user_info, dependent: :destroy
end
如果我尝试访问我的员工的first_name,即使该记录存在于Mongo文档中,它也会返回nil
在我的查询中,导致nil in-spite对象存在:
@employee = @company.employees
现在,如果我得到每个员工的first_name,结果为nil e.g。
@user = User.where(user_info: @employees.first)
@employee = @employees.first.user # this return null
它在查询下面触发并导致nil:
MOPED: 127.0.0.1:27017 QUERY database=quikchex_v2_development collection=users selector={"user_info_id"=>BSON::ObjectId('53d88cbf4e696b0bc2020000')} flags=[] limit=0 skip=0 batch_size=nil fields=nil runtime: 0.3662ms
如果我在mongo提示符上触发相同的查询,我会得到输出:
db.users.find({user_info_id: '53d88cbf4e696b0bc2020000'})
{ "_id" : ObjectId("53d88cbc4e696b0bc2000000"), "first_name" : "Nikunj", "last_name" : "Thakkar", "user_info_id" : "53d88cbf4e696b0bc2020000", "user_info_type" : "Employee" }
但是以下查询返回nil
db.users.find({user_info_id: ObjectId('53d88cbf4e696b0bc2020000')})
要注意的是rails在查询时将user_info_id转换为BSON :: ObjectId(' 53d88cbf4e696b0bc2020000'),它不应该
编辑: 我尝试了以下本机查询,它返回了员工对象:
User.collection.find({user_info_id: '53d88cbf4e696b0bc2020000'})
然后问题是mongoid在查询时将user_info_id转换为BSON :: ObjectId(' 53d88cbf4e696b0bc2020000'),它不应该