rails mongoid criteria find by association rails mongoid criteria find by association mongodb mongodb

rails mongoid criteria find by association


You have to keep in mind that there are no joins in mongodb. In relational dbs, includes forms a join query and you can use columns from both the tables in query. However due to absence of joins in mongodb, same is not possible.

In mongoid, includes just saves a bunch of db calls. It fetches and stores the associated records in identity map for fast retrieval, but still while querying, one query can only deal with one collection.

If you need articles based on user names, I would suggest following work around:

user_ids = User.where(username: 'erebus').only(:_id).map(&:_id)articles = Article.where(:user_id.in => user_ids)


You can make it little shorter from what rubish suggested:

user_ids = User.where(username: 'erebus').pluck(:id)articles = Article.where(:user_id.in => user_ids)

Or one liner:

articles = Article.where(:user_id.in => User.where(username: 'erebus').pluck(:id))