开发者

mongoid query rails 3

开发者 https://www.devze.com 2023-02-17 07:14 出处:网络
brand new to MongoDB / mongoid and still pretty green on ruby / rails on the rails console: t = Task.all(:conditions=> {:title => \"task2\"})

brand new to MongoDB / mongoid and still pretty green on ruby / rails

on the rails console:

t = Task.all(:conditions  => {:title => "task2"})

=> #<Mongoid::Criteria
selector: {:title=>"task2"},
options:  {},
class:    Task,
embedded: false>


>> t.first
=> #<Task _id: 4d7e2cdb73ec3227dd000009, title: "task2", latitude: 23.987904829, longitude: -12.9423875,  created_by: "4d792d6973ec3248e3000001">

returns what I would expect, but

t = Task.where(:created_by => "4d792d6973ec3248e3000001")

=> #<Mongoid::Criteria
selector: {:created_by=>BSON::ObjectId('4d792d6973ec3248e3000001')},
options:  {},
class:    Task,
embedded: false>

>> t.first 
=> nil

same result with:

t = Task.all(:conditions  => {:created_by => "4d792d6973ec3248e3000001"})

here is the model:

class Task
  include Mongoid::Document
  field :title
  field :latitude,                  :type => Float
  field :longitude,                 :type => Float
  field :created_by
end
开发者_开发百科

what am I doing wrong ?

updated example:

>> Task.new(:title => "task8", :created_by => "4d792d6973ec3248e3000001")
=> #<Task _id: 4d81037973ec32cc22000003, latitude: nil, longitude: nil, title: "task8", created_by: "4d792d6973ec3248e3000001">

>> t = Task.all(:conditions  => {:created_by => "4d792d6973ec3248e3000001"})
=> #<Mongoid::Criteria
selector: {:created_by=>BSON::ObjectId('4d792d6973ec3248e3000001')},
options:  {},
class:    Task,
embedded: false>

>> t.first 
=> nil

do I need to specifically define created_by as :type => String ?


Looks like created_by is stored as a string in your document, but then you query looking for an ObjectId. ObjectId's and strings aren't the same.

Try changing

>> Task.new(:title => "task8", :created_by => "4d792d6973ec3248e3000001")

to

>> Task.new(:title => "task8", :created_by => BSON::ObjectId("4d792d6973ec3248e3000001"))


You have to include this functionality in mongoid as explained in docs:

class Person
  include Mongoid::Document
  include Mongoid::Timestamps
end
0

精彩评论

暂无评论...
验证码 换一张
取 消