mongomapper association skips duplicates

孤街醉人 提交于 2019-12-02 19:43:41

问题


I have a Document with Array of ObjectId:

Class Task
  key :user_id, Array
  many :userlist, class_name: 'User', :in => :user_id

In that Array I store different user_id values, sometimes duplicated. I can see duplicated user_id's using:

@task.user_id.each do |z|
  puts z
end

But when I fetch and associate the data using:

@task.userlist.each do |z|
  puts z.name
end

I do not get the duplicates :(, only unique id's get associated. Why?


回答1:


What you are seeing is exactly correct from the definition of associations and the underlying query matching the "in" clause. Refresh you thinking of "in" as "in the set" of distinct objects http://en.wikipedia.org/wiki/Set_(mathematics) The fetch for userlist has an underlying query on the User collection with a $in clause, see http://docs.mongodb.org/manual/reference/operator/query/in/

For the @task.userlist association, you will get only the documents in the User collection that match the $in clause, the User collection is the primary "subject." There's a significant semantic difference from

User.where(:user_id.in => self.user_id)

versus

self.user_id.collect |user_id| do User.where(:user_id => user_id).first; end

In order to get "duplicates" from the former query, you would have to have duplicate documents in the User collection, seriously. ;-)

Hope that this helps your understanding.



来源:https://stackoverflow.com/questions/24814688/mongomapper-association-skips-duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!