mongoidmongoid4

How to find all document by association Mongoid 4


I have a model Tag which potentially belongs to several other models, but at the moment only one model Todo which in turn belongs to User like so:

class User
  include Mongoid::Document
  field: name,  type: String
  has_many :todos
end

class Todo
  include Mongoid::Document
  field: name,  type: String
  belongs_to :user
end

class Tag
  include Mongoid::Document
  field: name,  type: String
  belongs_to :todos
end

How can I query all Tags that belongs to a particular user? I've written the following:

todo_ids = Todo.where(user_id: '86876876787')

and then:

tags = Tag.where('todo_id.in': todo_ids)

But those didn't work. What am I missing?


Solution

  • You're missing two things:

    1. Mongoid isn't ActiveRecord so it won't know what to do with todo_ids in the Tag query.
    2. 'todo_id.in' is a field path that is trying to look at the in field inside a todo_id hash, this isn't a use of MongoDB's $in operator.

    You can only work with one collection at a time so to fix the first one, you need to pull an array of IDs out of MongoDB:

    todo_ids = Todo.where(user_id: '86876876787').pluck(:id)
    # -------------------------------------------^^^^^^^^^^^
    

    To fix the second one, use the $in operator:

    tags = Tag.where(todo_id: { '$in': todo_ids })
    tags = Tag.where(:todo_id.in => todo_ids)
    tags = Tag.in(todo_id: todo_ids)
    #...