【问题标题】:Search with Array of Ids使用 ID 数组搜索
【发布时间】:2014-04-04 05:22:37
【问题描述】:

假设我有两个模特帖子和类别。

Post has_many Categories

现在,我想根据类别搜索帖子?

例子:

Post 1 has categories 2,5,6

Post 2 has categories 5,9

Post 3 has categories 2,4,8,9

现在在搜索用户选择类别 2,4,8

在结果页面中,我想显示包含类别(2、4、8)的帖子

帖子 3

但是当我们使用返回 Post 1 和 post 3 的 IN 查询时。

我只想要帖子 3

【问题讨论】:

  • 加油,你可以做得更好。在征求建议之前先展示一些工作很重要。

标签: ruby ruby-on-rails-3 search activerecord


【解决方案1】:
categories_ids=[2,3,4]

@posts = Post.joins(:categories).
  where("categories.id IN (?) ",categories_ids).count(:group => "post_id") 

结果会是这样的:

{"1"=>2,"3"=>2}

在该哈希键中定义 Post id & value 定义匹配的类别数。

【讨论】:

    【解决方案2】:
    category_ids = [2,4,8]
    Post.select('posts.*')
         joins(:categories).
         where(categories: {id: category_ids}).
         group('posts.id').
         having('COUNT(categories.id) = ?', category_ids.size)
    

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      相关资源
      最近更新 更多