从Mongoid中的实例对象调用find(:all)

时间:2010-11-22 07:50:53

标签: mongodb mongoid

说我有以下对象:

{ "text" : "oa3", "topic_ids" : [ ObjectId("4cea00efd8030a35eb000004") ]}

我有一个代表这个名为“a”的对象

a.topics.find(:all).count  #this returns 0

我觉得我做错了。

如何检索此特定对象中主题的迭代器?

1 个答案:

答案 0 :(得分:4)

# get the number of topics
a.topics.count

# same but faster
a.topic_ids.count

# get an array of the topics
a.topics.entries

# do a query on the topics
a.topics.where(:title => 'Movies').entries

关键是使用Mongoid的标准(Model.whereModel.association.where)来执行查询而不是ActiveRecord样式查找器(Model.find)。 ActiveRecord风格的查找器实际上只是为了方便--Mongoid的真正力量在Criteria中。

有关Mongoid网站的更多信息:

http://mongoid.org/docs/querying/