轨道mongoid标准由协会找到 [英] rails mongoid criteria find by association
问题描述
我试图找到它包含在一个belongs_to的关系相关联的用户名的记录,但它不工作。
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)
工作正常,但我想使用的用户名是存储在用户表参照
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")
我也有 identity_map_enabled:真正的
Article.includes(:用户).inclusions
返回的关系细节
不工作,那我不理解?
推荐答案
您必须记住,有MongoDB中没有加入。在关系DBS,包括
形成连接查询,你可以从无论是在查询中的表使用的列。然而,由于缺少连接在mongodb的,同样是不可能的。
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.
在mongoid,包括
只是保存了一堆数据库调用。它获取并存储身份地图快速检索相关的记录,但还是在查询时,一个查询只能处理一个集合。
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)
这篇关于轨道mongoid标准由协会找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!