rails mongoid criteria find by association
Asked Answered
T

2

14

I'm trying to find a record by associated username which is included in a belongs_to relation, but it's not working.

Articles belong to Users Users have many articles

Article.where(user_id: someid) works fine, but I'd like to use the username as reference which is stored in the Users table.

Article.includes(:user).where(:username => "erebus")
Article.includes(:user).where("user.username" => "erebus")

I also have identity_map_enabled: true

Article.includes(:user).inclusions returns the relation details

Doesn't work, what am I not understanding?

Tumulus answered 3/4, 2012 at 10:13 Comment(0)
L
31

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)
Leathers answered 3/4, 2012 at 10:51 Comment(6)
what if we get the data from the other way and there's actually no array in the current collection, but the other one ?Clayclaybank
oh yes i know the answer : you can't.Clayclaybank
would this not increase the query complexity? what if we what the same result like joins or some alternative solutionCitystate
@JaiKumarRajput This is a very outdated solution, mongodb supports join like functionality now, please consult documentation.Leathers
Rubish, can you please suggest me some link or public assets where I can take help?Citystate
Also does mongoid help in same?Citystate
R
16

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))
Rhizopod answered 29/1, 2015 at 10:22 Comment(1)
would this not increase the query complexity? what if we what the same result like joins or some alternative solutionCitystate

© 2022 - 2024 — McMap. All rights reserved.