Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails mongoid criteria find by association

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?

like image 389
ere Avatar asked Apr 03 '12 10:04

ere


1 Answers

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)
like image 182
rubish Avatar answered Sep 30 '22 20:09

rubish