rails mongoid标准通过关联找到
我正在尝试通过关联的用户名来查找记录,该用户名包含在belongs_to关系中,但它不起作用。
文章属于用户用户有很多文章
Article.where(user_id: someid)
工作正常,但我想使用用户名作为参考,存储在Users表中。
Article.includes(:user).where(:username => "erebus") Article.includes(:user).where("user.username" => "erebus")
我也有identity_map_enabled: true
Article.includes(:user).inclusions
返回关系详细信息
不起作用,我不理解什么?
你必须记住mongodb中没有连接。 在关系数据库中, includes
表单连接查询,您可以使用查询中的两个表中的列。 但是由于mongodb没有连接,同样是不可能的。
在mongoid中, includes
只保存一堆db调用。 它在身份映射中获取并存储相关记录以便快速检索,但在查询时,一个查询只能处理一个集合。
如果您需要基于用户名的文章,我建议您进行以下解决方法:
user_ids = User.where(username: 'erebus').only(:_id).map(&:_id) articles = Article.where(:user_id.in => user_ids)
你可以根据rubish建议的那样缩短它:
user_ids = User.where(username: 'erebus').pluck(:id) articles = Article.where(:user_id.in => user_ids)
或者一个class轮:
articles = Article.where(:user_id.in => User.where(username: 'erebus').pluck(:id))
- has_many通过与现有对象/ ActiveRecord的关联
- rails has_many setter应该设置条件,如果指定的话
- Shoulda Matcher和has_many通过:未定义的方法`class_name’为nil:NilClass
- 获取fields_for和accepts_nested_attributes_for以使用belongs_to关系
- 关于Rails中正确关联的问题
- 检索给定用户评论的所有post,Ruby on Rails
- 外键(class_id)未在belongs_to关联中填充
- ActiveRecord:定义关联时,将类而不是字符串传递给class_name
- 与Chartkick和Rails的关联