rails mongoid criteria find by association

后端 未结 2 1006
滥情空心
滥情空心 2020-12-28 19:38

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 artic

相关标签:
2条回答
  • 2020-12-28 20:23

    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)
    
    0 讨论(0)
  • 2020-12-28 20:30

    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))
    
    0 讨论(0)
提交回复
热议问题