【问题标题】:Get children of a collection of parents with ActiveRecord使用 ActiveRecord 获取父母集合的孩子
【发布时间】:2016-09-21 09:25:30
【问题描述】:

我有一个具有一对多关系的 Category 模型和 Post 模型。

我想要特定类别的所有帖子。

我希望结果是一个 ActiveRecord 对象,以便能够进行进一步的查询。

现在我像这样使用.map

categories.map{|c| c.posts.order(position: :asc)}

【问题讨论】:

  • 问题是什么?
  • 如何使用 ActiveRecord 获取父母集合的所有孩子?

标签: ruby-on-rails ruby activerecord rails-activerecord ruby-on-rails-5


【解决方案1】:

对 Posts 使用嵌入式查询,如下:

Post.where(category_id: Category.all.pluck(:id)).order(position: :asc)

【讨论】:

    【解决方案2】:

    首先找到所有你感兴趣的分类并获取id:

    category_ids = Category.where('name like ?', '%foo%').pluck(:id)
    

    然后只需查询 category_id 包含在此 id 列表中的帖子:

    posts = Post.where(category_id: category_ids)
    

    这是一个AR对象,所以你可以继续添加orderwhere等等:

    posts.order(position: :asc)
    

    【讨论】:

    • 您忘记订购帖子
    • 添加了订单部分。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-10-06
    • 2015-08-30
    • 2021-12-02
    • 2013-06-04
    • 2015-08-21
    • 2018-01-29
    • 2011-03-24
    • 2013-04-10
    相关资源
    最近更新 更多