我有两个 Model 如下,奇怪的是如果我调用 Community 中的 activities 方法能返回查询结果,如果我直接查询 Activity 则无结果返回。百思不得其解呀!请看下面在 irb 中执行的结果,Mongoid::Criteria 的实例都一模一样!
class Activity
include Mongoid::Document
....
field target_object
end
class Community
include Mongoid::Document
....
def activities
Activity.where(target_object:{"id" => self.id, "type"=>"Community"})
end
end
--------------------------------------------------华丽的分割线-------------------------------------- Activity 实例例子
irb(main):002:0> Activity.last
=> #<Activity _id: 51e615b4f9dffbed71000002, _type: nil, created_at: 2013-07-17 03:55:32 UTC, updated_at: 2013-07-17 03:55:32 UTC, verb: :new_article, actor: {"id"=>"51e3661af9dffbce7c000001", "type"=>"User"}, object: {"id"=>"51e615b4f9dffbed71000001", "type"=>"Article"}, target_object: {"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"}, receivers: [{"id"=>"51e3fb35f9dffbafff000001", "type"=>"User"}]>
执行查询
irb(main):006:0> c = Community.first
=> #<Community _id: 51e37648f9dffb5e4c000013, _type: nil, created_at: 2013-07-15 04:10:48 UTC, updated_at: 2013-07-15 14:15:05 UTC, name: "Biboo World", brief: "精彩水世界", user_ids: ["51e3661af9dffbce7c000001", "51e3fb35f9dffbafff000001"]>
irb(main):007:0> c.activities
=> #<Mongoid::Criteria
selector: {"target_object"=>{"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"}}
options: {}
class: Activity
embedded: false>
irb(main):008:0> c.activities.count
=> 11
irb(main):015:0> Activity.where(target_object: {"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"})
=> #<Mongoid::Criteria
selector: {"target_object"=>{"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"}}
options: {}
class: Activity
embedded: false>
irb(main):014:0> Activity.where(target_object: {"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"}).count
=> 0